Let there be light

This commit is contained in:
PiggyPiglet
2026-01-20 21:23:37 +08:00
parent 2d9f4fca77
commit 722279308a
46 changed files with 1370 additions and 1957 deletions

View File

@@ -7,7 +7,7 @@ plugins {
} }
group = "at.helpch" group = "at.helpch"
version = "1.0.0" version = "1.0.0-experifuckingmental"
description = "An awesome placeholder provider!" description = "An awesome placeholder provider!"
@@ -24,11 +24,17 @@ dependencies {
} }
java { java {
sourceCompatibility = JavaVersion.VERSION_25 sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_25 targetCompatibility = JavaVersion.VERSION_21
withJavadocJar() withJavadocJar()
withSourcesJar() withSourcesJar()
disableAutoTargetJvm() disableAutoTargetJvm()
}
tasks {
processResources {
eachFile { expand("version" to project.version) }
}
} }

View File

@@ -20,11 +20,9 @@
package at.helpch.placeholderapi; package at.helpch.placeholderapi;
import com.google.common.collect.ImmutableSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -32,15 +30,11 @@ import java.util.stream.Collectors;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.Relational; import at.helpch.placeholderapi.expansion.Relational;
import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager;
import at.helpch.placeholderapi.replacer.CharsReplacer; import at.helpch.placeholderapi.replacer.CharsReplacer;
import at.helpch.placeholderapi.replacer.Replacer; import at.helpch.placeholderapi.replacer.Replacer;
import at.helpch.placeholderapi.replacer.Replacer.Closure; import at.helpch.placeholderapi.replacer.Replacer.Closure;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.OfflinePlayer; import com.hypixel.hytale.server.core.entity.entities.Player;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public final class PlaceholderAPI { public final class PlaceholderAPI {
@@ -68,12 +62,48 @@ public final class PlaceholderAPI {
* @return String containing all translated placeholders * @return String containing all translated placeholders
*/ */
@NotNull @NotNull
public static String setPlaceholders(final OfflinePlayer player, public static String setPlaceholders(final Player player,
@NotNull final String text) { @NotNull final String text) {
return REPLACER_PERCENT.apply(text, player, return REPLACER_PERCENT.apply(text, player,
PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); PlaceholderAPIPlugin.instance().localExpansionManager()::getExpansion);
} }
public static Message setPlaceholders(final Player player,
@NotNull final Message original) {
String replaced = setPlaceholders(player, original.getFormattedMessage().rawText);
String link = original.getFormattedMessage().link == null ? null : PlaceholderAPI.setPlaceholders(player, original.getFormattedMessage().link);
List<Message> newChildren = original.getChildren().stream()
.filter(Objects::nonNull)
.map(child -> setPlaceholders(player, child))
.toList();
Message message = Message.raw(replaced)
.color(original.getColor());
if (link != null) {
message = message.link(link);
}
int bold = original.getFormattedMessage().bold.getValue();
if (bold != 0) {
message = message.bold(bold != 1);
}
int italic = original.getFormattedMessage().italic.getValue();
if (italic != 0) {
message = message.italic(italic != 1);
}
return message.insertAll(newChildren);
}
// @NotNull
// public static Message setPlaceholders(final Player player,
// @NotNull final Message message) {
//
// }
/** /**
* Translates all placeholders into their corresponding values. * Translates all placeholders into their corresponding values.
* <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}. * <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}.
@@ -83,36 +113,36 @@ public final class PlaceholderAPI {
* @return String containing all translated placeholders * @return String containing all translated placeholders
*/ */
@NotNull @NotNull
public static List<String> setPlaceholders(final OfflinePlayer player, public static List<String> setPlaceholders(final Player player,
@NotNull final List<String> text) { @NotNull final List<String> text) {
return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList()); return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList());
} }
/** // /**
* Translates all placeholders into their corresponding values. // * Translates all placeholders into their corresponding values.
* <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}. // * <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}.
* // *
* @param player Player to parse the placeholders against // * @param player Player to parse the placeholders against
* @param text Text to set the placeholder values in // * @param text Text to set the placeholder values in
* @return String containing all translated placeholders // * @return String containing all translated placeholders
*/ // */
@NotNull // @NotNull
public static String setPlaceholders(final Player player, @NotNull String text) { // public static String setPlaceholders(final Player player, @NotNull String text) {
return setPlaceholders(((OfflinePlayer) player), text); // return setPlaceholders(((OfflinePlayer) player), text);
} // }
/** // /**
* Translates all placeholders into their corresponding values. // * Translates all placeholders into their corresponding values.
* <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}. // * <br>The pattern of a valid placeholder is {@literal %<identifier>_<params>%}.
* // *
* @param player Player to parse the placeholders against // * @param player Player to parse the placeholders against
* @param text List of Strings to set the placeholder values in // * @param text List of Strings to set the placeholder values in
* @return String containing all translated placeholders // * @return String containing all translated placeholders
*/ // */
@NotNull // @NotNull
public static List<String> setPlaceholders(final Player player, @NotNull List<@NotNull String> text) { // public static List<String> setPlaceholders(final Player player, @NotNull List<@NotNull String> text) {
return setPlaceholders(((OfflinePlayer) player), text); // return setPlaceholders(((OfflinePlayer) player), text);
} // }
/** /**
* Translates all placeholders into their corresponding values. * Translates all placeholders into their corresponding values.
@@ -123,10 +153,10 @@ public final class PlaceholderAPI {
* @return String containing all translated placeholders * @return String containing all translated placeholders
*/ */
@NotNull @NotNull
public static String setBracketPlaceholders(final OfflinePlayer player, public static String setBracketPlaceholders(final Player player,
@NotNull final String text) { @NotNull final String text) {
return REPLACER_BRACKET.apply(text, player, return REPLACER_BRACKET.apply(text, player,
PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); PlaceholderAPIPlugin.instance().localExpansionManager()::getExpansion);
} }
/** /**
@@ -138,37 +168,37 @@ public final class PlaceholderAPI {
* @return String containing all translated placeholders * @return String containing all translated placeholders
*/ */
@NotNull @NotNull
public static List<@NotNull String> setBracketPlaceholders(final OfflinePlayer player, public static List<@NotNull String> setBracketPlaceholders(final Player player,
@NotNull final List<@NotNull String> text) { @NotNull final List<@NotNull String> text) {
return text.stream().map(line -> setBracketPlaceholders(player, line)) return text.stream().map(line -> setBracketPlaceholders(player, line))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/** // /**
* Translates all placeholders into their corresponding values. // * Translates all placeholders into their corresponding values.
* <br>The pattern of a valid placeholder is {@literal {<identifier>_<params>}}. // * <br>The pattern of a valid placeholder is {@literal {<identifier>_<params>}}.
* // *
* @param player Player to parse the placeholders against // * @param player Player to parse the placeholders against
* @param text Text to set the placeholder values in // * @param text Text to set the placeholder values in
* @return String containing all translated placeholders // * @return String containing all translated placeholders
*/ // */
@NotNull // @NotNull
public static String setBracketPlaceholders(Player player, @NotNull String text) { // public static String setBracketPlaceholders(Player player, @NotNull String text) {
return setBracketPlaceholders((OfflinePlayer) player, text); // return setBracketPlaceholders((OfflinePlayer) player, text);
} // }
//
/** // /**
* Translates all placeholders into their corresponding values. // * Translates all placeholders into their corresponding values.
* <br>The pattern of a valid placeholder is {@literal {<identifier>_<params>}}. // * <br>The pattern of a valid placeholder is {@literal {<identifier>_<params>}}.
* // *
* @param player Player to parse the placeholders against // * @param player Player to parse the placeholders against
* @param text List of Strings to set the placeholder values in // * @param text List of Strings to set the placeholder values in
* @return String containing all translated placeholders // * @return String containing all translated placeholders
*/ // */
@NotNull // @NotNull
public static List<String> setBracketPlaceholders(Player player, @NotNull List<String> text) { // public static List<String> setBracketPlaceholders(Player player, @NotNull List<String> text) {
return setBracketPlaceholders((OfflinePlayer) player, text); // return setBracketPlaceholders((OfflinePlayer) player, text);
} // }
/** /**
* set relational placeholders in the text specified placeholders are matched with the pattern * set relational placeholders in the text specified placeholders are matched with the pattern
@@ -192,8 +222,8 @@ public final class PlaceholderAPI {
String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); String identifier = format.substring(0, index).toLowerCase(Locale.ROOT);
String params = format.substring(index + 1); String params = format.substring(index + 1);
final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() final PlaceholderExpansion expansion = PlaceholderAPIPlugin.instance()
.getLocalExpansionManager().getExpansion(identifier); .localExpansionManager().getExpansion(identifier);
if (!(expansion instanceof Relational)) { if (!(expansion instanceof Relational)) {
continue; continue;
@@ -230,7 +260,7 @@ public final class PlaceholderAPI {
* @return true if identifier is already registered * @return true if identifier is already registered
*/ */
public static boolean isRegistered(@NotNull final String identifier) { public static boolean isRegistered(@NotNull final String identifier) {
return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() return PlaceholderAPIPlugin.instance().localExpansionManager()
.findExpansionByIdentifier(identifier).isPresent(); .findExpansionByIdentifier(identifier).isPresent();
} }
@@ -241,8 +271,8 @@ public final class PlaceholderAPI {
*/ */
@NotNull @NotNull
public static Set<String> getRegisteredIdentifiers() { public static Set<String> getRegisteredIdentifiers() {
return ImmutableSet return Set
.copyOf(PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().getIdentifiers()); .copyOf(PlaceholderAPIPlugin.instance().localExpansionManager().getIdentifiers());
} }
/** /**
@@ -293,314 +323,4 @@ public final class PlaceholderAPI {
public static boolean containsBracketPlaceholders(String text) { public static boolean containsBracketPlaceholders(String text) {
return text != null && BRACKET_PLACEHOLDER_PATTERN.matcher(text).find(); 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<String, PlaceholderHook> 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<String> getRegisteredPlaceholderPlugins() {
return getRegisteredIdentifiers();
}
/**
* @return always null
* @deprecated Will be removed in a future release.
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.13.0")
public static Set<String> 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<String> setPlaceholders(OfflinePlayer player,
List<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 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<String> setPlaceholders(OfflinePlayer player, List<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 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<String> setPlaceholders(OfflinePlayer player, List<String> 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<String> setPlaceholders(Player player, List<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 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<String> setBracketPlaceholders(OfflinePlayer player, List<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 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<String> setBracketPlaceholders(Player player, List<String> text,
boolean colorize) {
return setBracketPlaceholders(player, text);
}
/**
* set relational placeholders in the text specified placeholders are matched with the pattern
* {@literal %<rel_(identifier)_(params)>%} 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.
* <br>The pattern of a valid placeholder is {@literal %rel_<identifier>_<params>%}.
*
* @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<String> setRelationalPlaceholders(Player one, Player two, List<String> text,
boolean colorize) {
return setRelationalPlaceholders(one, two, text);
}
} }

View File

@@ -1,44 +0,0 @@
package at.helpch.placeholderapi;
import at.helpch.placeholderapi.configuration.BooleanValue;
import at.helpch.placeholderapi.configuration.ConfigManager;
import at.helpch.placeholderapi.configuration.ExpansionSort;
import at.helpch.placeholderapi.configuration.PlaceholderAPIConfig;
import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager;
import com.hypixel.hytale.codec.builder.BuilderCodec;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.plugin.JavaPluginInit;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;
public class PlaceholderAPIBootstrap extends JavaPlugin {
private final ConfigManager configManager;
private final LocalExpansionManager localExpansionManager;
public PlaceholderAPIBootstrap(@NotNull final JavaPluginInit init) {
super(init);
configManager = new ConfigManager(this);
localExpansionManager = new LocalExpansionManager(this);
}
@Override
protected void setup() {
configManager.setup();
}
@Override
protected void start() {
super.start();
}
@Override
protected void shutdown() {
super.shutdown();
}
public LocalExpansionManager localExpansionManager() {
return localExpansionManager;
}
}

View File

@@ -1,296 +1,79 @@
/*
* This file is part of PlaceholderAPI
*
* PlaceholderAPI
* Copyright (c) 2015 - 2026 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 <http://www.gnu.org/licenses/>.
*/
package at.helpch.placeholderapi; package at.helpch.placeholderapi;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import at.helpch.placeholderapi.commands.PlaceholderCommandRouter; import at.helpch.placeholderapi.commands.PlaceholderCommandRouter;
import at.helpch.placeholderapi.configuration.PlaceholderAPIConfig; import at.helpch.placeholderapi.configuration.ConfigManager;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.manager.CloudExpansionManager; import at.helpch.placeholderapi.expansion.manager.CloudExpansionManager;
import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager; import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager;
import at.helpch.placeholderapi.listeners.ServerLoadEventListener; import at.helpch.placeholderapi.listeners.ServerLoadEventListener;
import at.helpch.placeholderapi.scheduler.UniversalScheduler; import com.hypixel.hytale.server.core.command.system.CommandSender;
import at.helpch.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; import com.hypixel.hytale.server.core.event.events.player.PlayerDisconnectEvent;
import at.helpch.placeholderapi.updatechecker.UpdateChecker; import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import at.helpch.placeholderapi.util.ExpansionSafetyCheck; import com.hypixel.hytale.server.core.plugin.JavaPluginInit;
import at.helpch.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; import org.jetbrains.annotations.NotNull;
/** public class PlaceholderAPIPlugin extends JavaPlugin {
* Yes I have a shit load of work to do... private final ConfigManager configManager = new ConfigManager(this);
* private final LocalExpansionManager localExpansionManager = new LocalExpansionManager(this);
* @author Ryan McCarthy private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this);
*/
public final class PlaceholderAPIPlugin extends JavaPlugin {
@NotNull
private static final Version VERSION;
private static PlaceholderAPIPlugin instance; private static PlaceholderAPIPlugin instance;
static { public static PlaceholderAPIPlugin instance() {
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; return instance;
} }
/** public PlaceholderAPIPlugin(@NotNull final JavaPluginInit init) {
* Get the configurable {@linkplain String} value that should be returned when a boolean is true super(init);
*
* @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; instance = this;
} }
@Override @Override
public void onEnable() { protected void setup() {
if (safetyCheck) { configManager.setup();
return; getEventRegistry().register(PlayerDisconnectEvent.class, localExpansionManager::onQuit);
if (configManager.config().cloudEnabled()) {
cloudExpansionManager.load();
} }
setupCommand(); new ServerLoadEventListener(this);
setupMetrics();
setupExpansions();
adventure = BukkitAudiences.create(this);
if (config.isCloudEnabled()) {
getCloudExpansionManager().load();
}
if (config.checkUpdates()) {
new UpdateChecker(this).fetch();
}
} }
@Override @Override
public void onDisable() { protected void start() {
if (safetyCheck) { getCommandRegistry().registerCommand(new PlaceholderCommandRouter(this));
return; super.start();
}
getCloudExpansionManager().kill();
getLocalExpansionManager().kill();
HandlerList.unregisterAll(this);
scheduler.cancelTasks(this);
adventure.close();
adventure = null;
instance = null;
} }
public void reloadConf(@NotNull final CommandSender sender) { @Override
getLocalExpansionManager().kill(); protected void shutdown() {
super.shutdown();
}
reloadConfig(); public void reloadPlugin(@NotNull final CommandSender sender) {
localExpansionManager.kill();
// configManager.save();
configManager.setup();
getLocalExpansionManager().load(sender); localExpansionManager.load(sender);
if (config.isCloudEnabled()) { if (configManager.config().cloudEnabled()) {
getCloudExpansionManager().load(); cloudExpansionManager.load();
} else { } else {
getCloudExpansionManager().kill(); cloudExpansionManager.kill();
} }
} }
@NotNull public LocalExpansionManager localExpansionManager() {
public LocalExpansionManager getLocalExpansionManager() {
return localExpansionManager; return localExpansionManager;
} }
@NotNull public ConfigManager configManager() {
public CloudExpansionManager getCloudExpansionManager() { return configManager;
}
public CloudExpansionManager cloudExpansionManager() {
return cloudExpansionManager; 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<String, Integer> 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);
}
}
} }

View File

@@ -20,19 +20,20 @@
package at.helpch.placeholderapi; package at.helpch.placeholderapi;
import org.bukkit.OfflinePlayer; import com.hypixel.hytale.server.core.entity.entities.Player;
import org.bukkit.entity.Player; import com.hypixel.hytale.server.core.universe.PlayerRef;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public abstract class PlaceholderHook { public abstract class PlaceholderHook {
@Nullable @Nullable
public String onRequest(final OfflinePlayer player, @NotNull final String params) { public String onRequest(final Player player, @NotNull final String params) {
if (player != null && player.isOnline()) { // Player player2;
return onPlaceholderRequest(player.getPlayer(), params); // if (player != null && player.isOnline()) {
} // return onPlaceholderRequest(player.getPlayer(), params);
// }
return onPlaceholderRequest(null, params); return onPlaceholderRequest(player, params);
} }
@Nullable @Nullable

View File

@@ -26,7 +26,6 @@ import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPIBootstrap;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.hypixel.hytale.server.core.command.system.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -46,7 +45,7 @@ public abstract class PlaceholderCommand {
protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) { protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) {
this.label = label; this.label = label;
this.alias = Sets.newHashSet(alias); this.alias = Set.of(alias);
setPermission("placeholderapi." + label); setPermission("placeholderapi." + label);
} }
@@ -97,13 +96,13 @@ public abstract class PlaceholderCommand {
this.permission = permission; this.permission = permission;
} }
public void evaluate(@NotNull final PlaceholderAPIBootstrap plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
} }
public void complete(@NotNull final PlaceholderAPIBootstrap plugin, public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {

View File

@@ -25,20 +25,10 @@ import java.awt.*;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.impl.cloud.CommandECloud; import at.helpch.placeholderapi.commands.impl.cloud.CommandECloud;
import at.helpch.placeholderapi.commands.impl.local.CommandDump; import at.helpch.placeholderapi.commands.impl.local.*;
import at.helpch.placeholderapi.commands.impl.local.CommandExpansionRegister;
import at.helpch.placeholderapi.commands.impl.local.CommandExpansionUnregister;
import at.helpch.placeholderapi.commands.impl.local.CommandHelp;
import at.helpch.placeholderapi.commands.impl.local.CommandInfo;
import at.helpch.placeholderapi.commands.impl.local.CommandList;
import at.helpch.placeholderapi.commands.impl.local.CommandParse;
import at.helpch.placeholderapi.commands.impl.local.CommandReload;
import at.helpch.placeholderapi.commands.impl.local.CommandVersion;
import at.helpch.placeholderapi.util.Msg;
import com.hypixel.hytale.server.core.Message; import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.*; import com.hypixel.hytale.server.core.command.system.*;
import com.hypixel.hytale.server.core.command.system.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
@@ -67,10 +57,14 @@ public final class PlaceholderCommandRouter extends AbstractCommand {
@Unmodifiable @Unmodifiable
private final Map<String, PlaceholderCommand> commands; private final Map<String, PlaceholderCommand> commands;
@Override
public String getName() {
return "papi";
}
public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) { public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) {
super("papi", "PlaceholderAPI Command"); super("papi", "papi");
addAliases("placeholderapi"); // addAliases("placeholderapi");
setAllowsExtraArguments(true); setAllowsExtraArguments(true);
this.plugin = plugin; this.plugin = plugin;
@@ -88,7 +82,7 @@ public final class PlaceholderCommandRouter extends AbstractCommand {
@NotNull @NotNull
public CompletableFuture<Void> acceptCall(@NotNull final CommandSender sender, @NotNull final ParserContext parserContext, public CompletableFuture<Void> acceptCall(@NotNull final CommandSender sender, @NotNull final ParserContext parserContext,
@NotNull final ParseResult parseResult) { @NotNull final ParseResult parseResult) {
final String[] args = parserContext.getInputString().split(" "); final String[] args = parserContext.getInputString().replace("papi ", "").split(" ");
if (args.length == 0) { if (args.length == 0) {
final PlaceholderCommand fallback = commands.get("version"); final PlaceholderCommand fallback = commands.get("version");

View File

@@ -20,25 +20,21 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
import java.util.Collection; import java.awt.*;
import java.util.*;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Stream;
public final class CommandECloud extends PlaceholderCommand { public final class CommandECloud extends PlaceholderCommand {
@Unmodifiable @Unmodifiable
private static final List<PlaceholderCommand> COMMANDS = ImmutableList private static final List<PlaceholderCommand> COMMANDS = List
.of(new CommandECloudClear(), .of(new CommandECloudClear(),
new CommandECloudStatus(), new CommandECloudStatus(),
new CommandECloudUpdate(), new CommandECloudUpdate(),
@@ -61,13 +57,13 @@ public final class CommandECloud extends PlaceholderCommand {
public CommandECloud() { public CommandECloud() {
super("ecloud"); super("ecloud");
final ImmutableMap.Builder<String, PlaceholderCommand> commands = ImmutableMap.builder(); final Map<String, PlaceholderCommand> commands = new HashMap<>();
for (final PlaceholderCommand command : COMMANDS) { for (final PlaceholderCommand command : COMMANDS) {
command.getLabels().forEach(label -> commands.put(label, command)); command.getLabels().forEach(label -> commands.put(label, command));
} }
this.commands = commands.build(); this.commands = commands;
} }
@@ -76,25 +72,50 @@ public final class CommandECloud extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, Message message = Message.empty()
"&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ", .insert(Message.raw("PlaceholderAPI ").color(Color.CYAN).bold(true))
" ", .insert(Message.raw("- ").color(Color.DARK_GRAY))
"&b/papi &fecloud status", .insert(Message.raw("eCloud Help Menu ").color(Color.GRAY))
" &7&oView status of the eCloud", .insert(Message.raw("-\n\n").color(Color.DARK_GRAY));
"&b/papi &fecloud list <all/{author}/installed> {page}",
" &7&oList all/author specific available expansions", final List<String[]> commands = List.of(
"&b/papi &fecloud info <expansion name> {version}", new String[]{"ecloud status", "View status of the eCloud"},
" &7&oView information about a specific expansion available on the eCloud", new String[]{"ecloud list <all/{author}/installed> {page}", "List all/author specific available expansions"},
"&b/papi &fecloud placeholders <expansion name>", new String[]{"ecloud info <expansion name> {version}", "View information about a specific expansion available on the eCloud"},
" &7&oView placeholders for an expansion", new String[]{"ecloud placeholders <expansion name>", "View placeholders for an expansion"},
"&b/papi &fecloud download <expansion name> {version}", new String[]{"ecloud download <expansion name> {version}", "Download an expansion from the eCloud"},
" &7&oDownload an expansion from the eCloud", new String[]{"ecloud update <expansion name/all>", "Update a specific/all installed expansions"},
"&b/papi &fecloud update <expansion name/all>", new String[]{"ecloud refresh", "Fetch the most up to date list of expansions available."},
" &7&oUpdate a specific/all installed expansions", new String[]{"ecloud clear", "Clear the expansion cloud cache."}
"&b/papi &fecloud refresh", );
" &7&oFetch the most up to date list of expansions available.",
"&b/papi &fecloud clear", for (String[] command : commands) {
" &7&oClear the expansion cloud cache."); message = message.insert(Message.raw("/papi").color(Color.CYAN))
.insert(Message.raw(command[0]).color(Color.WHITE))
.insert(Message.raw("\n " + command[1]).color(Color.GRAY));
}
sender.sendMessage(message);
// Msg.msg(sender,
// "&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ",
// " ",
// "&b/papi &fecloud status",
// " &7&oView status of the eCloud",
// "&b/papi &fecloud list <all/{author}/installed> {page}",
// " &7&oList all/author specific available expansions",
// "&b/papi &fecloud info <expansion name> {version}",
// " &7&oView information about a specific expansion available on the eCloud",
// "&b/papi &fecloud placeholders <expansion name>",
// " &7&oView placeholders for an expansion",
// "&b/papi &fecloud download <expansion name> {version}",
// " &7&oDownload an expansion from the eCloud",
// "&b/papi &fecloud update <expansion name/all>",
// " &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; return;
} }
@@ -103,44 +124,47 @@ public final class CommandECloud extends PlaceholderCommand {
final PlaceholderCommand target = commands.get(search); final PlaceholderCommand target = commands.get(search);
if (target == null) { if (target == null) {
Msg.msg(sender, "&cUnknown command &7ecloud " + search); sender.sendMessage(Message.raw("Unknown command ").color(Color.RED).insert(Message.raw("ecloud " + search).color(Color.GRAY)));
// Msg.msg(sender, "&cUnknown command &7ecloud " + search);
return; return;
} }
final String permission = target.getPermission(); final String permission = target.getPermission();
if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) {
Msg.msg(sender, "&cYou do not have permission to do this!"); sender.sendMessage(Message.raw("You do not have permission to do this!").color(Color.RED));
// Msg.msg(sender, "&cYou do not have permission to do this!");
return; return;
} }
if (!plugin.getPlaceholderAPIConfig().isCloudEnabled()) { if (!plugin.configManager().config().cloudEnabled()) {
Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."); sender.sendMessage(Message.raw("The eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."));
// Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin.");
return; return;
} }
target.evaluate(plugin, sender, search, params.subList(1, params.size())); target.evaluate(plugin, sender, search, params.subList(1, params.size()));
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() <= 1) { // if (params.size() <= 1) {
final Stream<String> targets = filterByPermission(sender, commands.values().stream()) // final Stream<String> targets = filterByPermission(sender, commands.values().stream())
.map(PlaceholderCommand::getLabels).flatMap(Collection::stream); // .map(PlaceholderCommand::getLabels).flatMap(Collection::stream);
suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0)); // suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0));
//
return; // send sub commands // return; // send sub commands
} // }
//
final String search = params.get(0).toLowerCase(Locale.ROOT); // final String search = params.get(0).toLowerCase(Locale.ROOT);
final PlaceholderCommand target = commands.get(search); // final PlaceholderCommand target = commands.get(search);
//
if (target == null) { // if (target == null) {
return; // return;
} // }
//
target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); // target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions);
} // }
} }

View File

@@ -20,12 +20,13 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import java.awt.*;
import java.util.List; import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -39,9 +40,10 @@ public final class CommandECloudClear extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
plugin.getCloudExpansionManager().clean(); plugin.cloudExpansionManager().clean();
Msg.msg(sender, sender.sendMessage(Message.raw("The eCloud cache has been cleared!").color(Color.GREEN));
"&aThe eCloud cache has been cleared!"); // Msg.msg(sender,
// "&aThe eCloud cache has been cleared!");
} }
} }

View File

@@ -20,16 +20,15 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import java.awt.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -54,22 +53,25 @@ public final class CommandECloudDownload extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must supply the name of an expansion.").color(Color.RED));
"&cYou must supply the name of an expansion."); // Msg.msg(sender,
// "&cYou must supply the name of an expansion.");
return; return;
} }
if (isBlockedExpansion(params.get(0))) { if (isBlockedExpansion(params.get(0))) {
Msg.msg(sender, sender.sendMessage(Message.raw("This expansion can't be downloaded.").color(Color.RED));
"&cThis expansion can't be downloaded."); // Msg.msg(sender,
// "&cThis expansion can't be downloaded.");
return; return;
} }
final CloudExpansion expansion = plugin.getCloudExpansionManager() final CloudExpansion expansion = plugin.cloudExpansionManager()
.findCloudExpansionByName(params.get(0)).orElse(null); .findCloudExpansionByName(params.get(0)).orElse(null);
if (expansion == null) { if (expansion == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Failed to find an expansion named: ").color(Color.GREEN).insert(Message.raw(params.get(0)).color(Color.WHITE)));
"&cFailed to find an expansion named: &f" + params.get(0)); // Msg.msg(sender,
// "&cFailed to find an expansion named: &f" + params.get(0));
return; return;
} }
@@ -77,64 +79,81 @@ public final class CommandECloudDownload extends PlaceholderCommand {
if (params.size() < 2) { if (params.size() < 2) {
version = expansion.getVersion(expansion.getLatestVersion()); version = expansion.getVersion(expansion.getLatestVersion());
if (version == null) { if (version == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Could not find latest version for expansion.").color(Color.RED));
"&cCould not find latest version for expansion."); // Msg.msg(sender,
// "&cCould not find latest version for expansion.");
return; return;
} }
} else { } else {
version = expansion.getVersion(params.get(1)); version = expansion.getVersion(params.get(1));
if (version == null) { if (version == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Could not find specified version: ").color(Color.RED)
"&cCould not find specified version: &f" + params.get(1), .insert(Message.raw(params.get(0) + "\n").color(Color.WHITE))
"&7Available versions: &f" + expansion.getAvailableVersions()); .insert(Message.raw("Available versions: ").color(Color.GRAY))
.insert(Message.raw(expansion.getAvailableVersions().toString()).color(Color.WHITE)));
// Msg.msg(sender,
// "&cCould not find specified version: &f" + params.get(1),
// "&7Available versions: &f" + expansion.getAvailableVersions());
return; return;
} }
} }
if (!version.isVerified()) { 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"); sender.sendMessage(Message.raw("The expansion: '").color(Color.RED)
.insert(Message.raw(params.get(0)).color(Color.WHITE))
.insert(Message.raw("' is not verified and can only be downloaded manually from ").color(Color.RED))
.insert(Message.raw("https://ecloud.placeholderapi.com").color(Color.WHITE)));
// 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; return;
} }
plugin.getCloudExpansionManager().downloadExpansion(expansion, version) plugin.cloudExpansionManager().downloadExpansion(expansion, version)
.whenComplete((file, exception) -> { .whenComplete((file, exception) -> {
if (exception != null) { if (exception != null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Failed to download expansion: ").color(Color.RED).insert(Message.raw(exception.getMessage()).color(Color.WHITE)));
"&cFailed to download expansion: &f" + exception.getMessage()); // Msg.msg(sender,
// "&cFailed to download expansion: &f" + exception.getMessage());
return; return;
} }
Msg.msg(sender, sender.sendMessage(Message.raw("Successfully downloaded expansion ").color(Color.GREEN)
"&aSuccessfully downloaded expansion &f" + expansion.getName() + " [" + version .insert(Message.raw(expansion.getName() + " [" + version.getVersion() + "] ").color(Color.WHITE))
.getVersion() + "] &ato file: &f" + file.getName(), .insert(Message.raw("to file: ").color(Color.GREEN))
"&aMake sure to type &f/papi reload &ato enable your new expansion!"); .insert(Message.raw(file.getName()).color(Color.WHITE))
.insert(Message.raw("\nMake sure to type ").color(Color.GREEN))
.insert(Message.raw("/papi reload ").color(Color.GREEN))
.insert(Message.raw("to enable your new expansion!").color(Color.WHITE)));
// 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(); plugin.cloudExpansionManager().load();
}); });
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) { // if (params.size() > 2) {
return; // return;
} // }
//
if (params.size() <= 1) { // if (params.size() <= 1) {
final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values() // final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values()
.stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); // .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_'));
suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); // suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0));
return; // return;
} // }
//
final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager() // final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager()
.findCloudExpansionByName(params.get(0)); // .findCloudExpansionByName(params.get(0));
if (!expansion.isPresent()) { // if (!expansion.isPresent()) {
return; // return;
} // }
//
suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); // suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1));
} // }
} }

View File

@@ -20,15 +20,14 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import java.awt.*;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -43,16 +42,18 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must specify the name of the expansion.").color(Color.RED));
"&cYou must specify the name of the expansion."); // Msg.msg(sender,
// "&cYou must specify the name of the expansion.");
return; return;
} }
final CloudExpansion expansion = plugin.getCloudExpansionManager() final CloudExpansion expansion = plugin.cloudExpansionManager()
.findCloudExpansionByName(params.get(0)).orElse(null); .findCloudExpansionByName(params.get(0)).orElse(null);
if (expansion == null) { if (expansion == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("There is no expansion with the name: ").color(Color.RED).insert(Message.raw(params.get(0)).color(Color.WHITE)));
"&cThere is no expansion with the name: &f" + params.get(0)); // Msg.msg(sender,
// "&cThere is no expansion with the name: &f" + params.get(0));
return; return;
} }
@@ -83,9 +84,13 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand {
} else { } else {
final CloudExpansion.Version version = expansion.getVersion(params.get(1)); final CloudExpansion.Version version = expansion.getVersion(params.get(1));
if (version == null) { if (version == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Could not find specified version: ").color(Color.RED)
"&cCould not find specified version: &f" + params.get(1), .insert(Message.raw(params.get(1)).color(Color.WHITE))
"&aVersions: &f" + expansion.getAvailableVersions()); .insert(Message.raw("\nVersions: ").color(Color.GREEN))
.insert(Message.raw(expansion.getAvailableVersions().toString()).color(Color.WHITE)));
// Msg.msg(sender,
// "&cCould not find specified version: &f" + params.get(1),
// "&aVersions: &f" + expansion.getAvailableVersions());
return; return;
} }
@@ -103,31 +108,31 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand {
.append('\n'); .append('\n');
} }
Msg.msg(sender, builder.toString()); sender.sendMessage(Message.raw(builder.toString())); // todo: convert colors
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) { // if (params.size() > 2) {
return; // return;
} // }
//
if (params.size() <= 1) { // if (params.size() <= 1) {
final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values() // final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values()
.stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); // .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_'));
suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); // suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0));
return; // return;
} // }
//
final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager() // final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager()
.findCloudExpansionByName(params.get(0)); // .findCloudExpansionByName(params.get(0));
if (!expansion.isPresent()) { // if (!expansion.isPresent()) {
return; // return;
} // }
//
suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); // suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1));
} // }
} }

View File

@@ -20,40 +20,26 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import com.google.common.base.Strings; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.google.common.collect.ImmutableSet; import at.helpch.placeholderapi.util.Format;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import java.awt.*;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.configuration.ExpansionSort;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Format; import com.hypixel.hytale.server.core.Message;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.command.system.CommandSender;
import net.kyori.adventure.text.Component; import com.hypixel.hytale.server.core.entity.entities.Player;
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.NotNull;
import org.jetbrains.annotations.Unmodifiable; 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 { public final class CommandECloudExpansionList extends PlaceholderCommand {
private static final int PAGE_SIZE = 10; private static final int PAGE_SIZE = 10;
@@ -73,13 +59,13 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
expansion -> "&f" + expansion.getLatestVersion(); expansion -> "&f" + expansion.getLatestVersion();
@NotNull @NotNull
private static final Function<CloudExpansion, Object> EXPANSION_CURRENT_VERSION = private static final Function<CloudExpansion, Object> EXPANSION_CURRENT_VERSION =
expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() expansion -> "&f" + PlaceholderAPIPlugin.instance().localExpansionManager()
.findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion) .findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion)
.orElse("Unknown"); .orElse("Unknown");
@Unmodifiable @Unmodifiable
private static final Set<String> OPTIONS = ImmutableSet.of("all", "installed"); private static final Set<String> OPTIONS = Set.of("all", "installed");
public CommandECloudExpansionList() { public CommandECloudExpansionList() {
@@ -91,11 +77,11 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
@NotNull final PlaceholderAPIPlugin plugin) { @NotNull final PlaceholderAPIPlugin plugin) {
switch (target.toLowerCase(Locale.ROOT)) { switch (target.toLowerCase(Locale.ROOT)) {
case "all": case "all":
return plugin.getCloudExpansionManager().getCloudExpansions().values(); return plugin.cloudExpansionManager().getCloudExpansions().values();
case "installed": case "installed":
return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); return plugin.cloudExpansionManager().getCloudExpansionsInstalled().values();
default: default:
return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); return plugin.cloudExpansionManager().getCloudExpansionsByAuthor(target).values();
} }
} }
@@ -137,78 +123,78 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
.append("&r"); .append("&r");
} }
private static Component getMessage(@NotNull final List<CloudExpansion> expansions, private static Message getMessage(@NotNull final List<CloudExpansion> expansions,
final int page, final int limit, @NotNull final String target) { final int page, final int limit, @NotNull final String target) {
final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); final SimpleDateFormat format = new SimpleDateFormat(PlaceholderAPIPlugin.instance().configManager().config().dateFormat());
final TextComponent.Builder message = text(); Message message = Message.empty();
for (int index = 0; index < expansions.size(); index++) { for (int index = 0; index < expansions.size(); index++) {
final CloudExpansion expansion = expansions.get(index); final CloudExpansion expansion = expansions.get(index);
final TextComponent.Builder line = text(); Message line = Message.empty();
final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1; final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1;
line.append(text(expansionNumber + ". ", DARK_GRAY)); line = line.insert(Message.raw(expansionNumber + ". ").color(Color.DARK_GRAY));
final NamedTextColor expansionColour; final Color expansionColour;
if (expansion.shouldUpdate()) { if (expansion.shouldUpdate()) {
expansionColour = GOLD; expansionColour = Color.YELLOW;
} else { } else {
if (expansion.hasExpansion()) { if (expansion.hasExpansion()) {
expansionColour = GREEN; expansionColour = Color.GREEN;
} else { } else {
expansionColour = GRAY; expansionColour = Color.GRAY;
} }
} }
line.append(text(expansion.getName(), expansionColour)); line = line.insert(Message.raw(expansion.getName()).color(expansionColour));
line.clickEvent(ClickEvent.suggestCommand("/papi ecloud download " + expansion.getName())); // line = line.click(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))
// );
final TextComponent.Builder hoverText = text("Click to download this expansion!", AQUA) // line.hoverEvent(HoverEvent.showText(hoverText.build()));
.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) { if (index != expansions.size() - 1) {
line.append(newline()); line.insert(Message.raw("\n"));
} }
message.append(line.build()); message = message.insert(line);
} }
if (limit > 1) { if (limit > 1) {
message.append(newline()); message = message.insert("\n");
final TextComponent.Builder left = text("", page > 1 ? GRAY : DARK_GRAY).toBuilder(); // Message left = Message.raw("◀", page > 1 ? GRAY : DARK_GRAY).toBuilder();
if (page > 1) { // if (page > 1) {
left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1))); // left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1)));
} // }
//
// final TextComponent.Builder right = text("▶", page < limit ? GRAY : DARK_GRAY).toBuilder();
final TextComponent.Builder right = text("", page < limit ? GRAY : DARK_GRAY).toBuilder(); // if (page < limit) {
// right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1)));
// }
if (page < limit) { message = message.insert(Message.raw(" - " + page + " - ").color(Color.GREEN));
right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1)));
}
message.append(left, text(" " + page + " ", GREEN), right);
} }
return message.build(); return message;
} }
private static void addExpansionTable(@NotNull final List<CloudExpansion> expansions, private static void addExpansionTable(@NotNull final List<CloudExpansion> expansions,
@@ -240,7 +226,10 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
return; return;
} }
table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2)));
// table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2)));
table.add(1, "&8" + "-".repeat(table.get(0).length() - (rows.getFirst().size() * 2)));
message.append(String.join("\n", table)); message.append(String.join("\n", table));
} }
@@ -250,23 +239,24 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must specify an option. [all, {author}, installed]").color(Color.RED));
"&cYou must specify an option. [all, {author}, installed]"); // Msg.msg(sender,
// "&cYou must specify an option. [all, {author}, installed]");
return; return;
} }
final boolean installed = params.get(0).equalsIgnoreCase("installed"); final boolean installed = params.get(0).equalsIgnoreCase("installed");
final List<CloudExpansion> expansions = Lists final List<CloudExpansion> expansions = new ArrayList<>(getExpansions(params.get(0), plugin));
.newArrayList(getExpansions(params.get(0), plugin));
if (expansions.isEmpty()) { if (expansions.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("No expansions available to list.").color(Color.RED));
"&cNo expansions available to list."); // Msg.msg(sender,
// "&cNo expansions available to list.");
return; return;
} }
expansions expansions
.sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); .sort(plugin.configManager().config().cloudSorting());
if (!(sender instanceof Player) && params.size() < 2) { if (!(sender instanceof Player) && params.size() < 2) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
@@ -278,7 +268,8 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
installed ? "&9Version" : "&9Latest Version", installed ? "&9Version" : "&9Latest Version",
installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION);
Msg.msg(sender, builder.toString()); sender.sendMessage(Message.raw(builder.toString()));
// Msg.msg(sender, builder.toString());
return; return;
} }
@@ -288,18 +279,27 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
page = 1; page = 1;
} else { } else {
//noinspection UnstableApiUsage //noinspection UnstableApiUsage
final Integer parsed = Ints.tryParse(params.get(1)); Integer parsed/* = Ints.tryParse(params.get(1))*/;
try {
parsed = Integer.parseInt(params.get(1));
} catch (Exception e) {
parsed = null;
}
if (parsed == null) { if (parsed == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Page number must be an integer.").color(Color.RED));
"&cPage number must be an integer."); // Msg.msg(sender,
// "&cPage number must be an integer.");
return; return;
} }
final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE);
if (parsed < 1 || parsed > limit) { if (parsed < 1 || parsed > limit) {
Msg.msg(sender, sender.sendMessage(Message.raw("Page number must be in the range [1.." + limit + "]").color(Color.RED)); //todo: not exact
"&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); // Msg.msg(sender,
// "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]");
return; return;
} }
@@ -318,37 +318,40 @@ public final class CommandECloudExpansionList extends PlaceholderCommand {
installed ? "&9Version" : "&9Latest Version", installed ? "&9Version" : "&9Latest Version",
installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION);
Msg.msg(sender, builder.toString()); sender.sendMessage(Message.raw(builder.toString()));
// Msg.msg(sender, builder.toString());
return; return;
} }
Msg.msg(sender, builder.toString()); sender.sendMessage(Message.raw(builder.toString()));
// Msg.msg(sender, builder.toString());
final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); 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); // final Component message = getMessage(values, page, limit, params.get(0));
// plugin.getAdventure().player((Player) sender).sendMessage(message);
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) { // if (params.size() > 2) {
return; // return;
} // }
//
if (params.size() <= 1) { // if (params.size() <= 1) {
suggestByParameter( // suggestByParameter(
Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) // Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors())
.stream(), suggestions, params.isEmpty() ? null : params.get(0)); // .stream(), suggestions, params.isEmpty() ? null : params.get(0));
return; // return;
} // }
//
suggestByParameter(IntStream.rangeClosed(1, // suggestByParameter(IntStream.rangeClosed(1,
(int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)) // (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE))
.mapToObj(Objects::toString), suggestions, params.get(1)); // .mapToObj(Objects::toString), suggestions, params.get(1));
} // }
} }

View File

@@ -20,17 +20,17 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import com.google.common.collect.Lists; import java.awt.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.IntStream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -45,52 +45,57 @@ public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must specify the name of the expansion.").color(Color.RED));
"&cYou must specify the name of the expansion."); // Msg.msg(sender,
// "&cYou must specify the name of the expansion.");
return; return;
} }
final CloudExpansion expansion = plugin.getCloudExpansionManager() final CloudExpansion expansion = plugin.cloudExpansionManager()
.findCloudExpansionByName(params.get(0)).orElse(null); .findCloudExpansionByName(params.get(0)).orElse(null);
if (expansion == null) { if (expansion == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("There is no expansion with the name: ").color(Color.RED).insert(Message.raw(params.getFirst()).color(Color.WHITE)));
"&cThere is no expansion with the name: &f" + params.get(0)); // Msg.msg(sender,
// "&cThere is no expansion with the name: &f" + params.get(0));
return; return;
} }
final List<String> placeholders = expansion.getPlaceholders(); final List<String> placeholders = expansion.getPlaceholders();
if (placeholders == null || placeholders.isEmpty()) { if (placeholders == null || placeholders.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("The expansion specified does not have placeholders listed.").color(Color.RED));
"&cThe expansion specified does not have placeholders listed."); // Msg.msg(sender,
// "&cThe expansion specified does not have placeholders listed.");
return; return;
} }
final List<List<String>> partitions = Lists // final List<List<String>> partitions = Lists
.partition(placeholders.stream().sorted().collect(Collectors.toList()), 10); // .partition(placeholders.stream().sorted().collect(Collectors.toList()), 10);
final List<List<String>> partitions = new ArrayList<>(IntStream.range(0, placeholders.size()).boxed().collect(Collectors.groupingBy(i -> i/10, Collectors.mapping(placeholders::get, Collectors.toList()))).values());
Msg.msg(sender, sender.sendMessage(Message.raw("&6 " + placeholders.size() + " &7 placeholders: &a\n" + partitions.stream().map(p -> String.join(", ", p)).collect(Collectors.joining("\n"))));
"&6" + placeholders.size() + "&7 placeholders: &a", // Msg.msg(sender,
partitions.stream().map(partition -> String.join(", ", partition)) // "&6" + placeholders.size() + "&7 placeholders: &a",
.collect(Collectors.joining("\n"))); // partitions.stream().map(partition -> String.join(", ", partition))
// .collect(Collectors.joining("\n")));
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) { // if (params.size() > 1) {
return; // return;
} // }
//
final Stream<String> names = plugin.getCloudExpansionManager() // final Stream<String> names = plugin.getCloudExpansionManager()
.getCloudExpansions() // .getCloudExpansions()
.values() // .values()
.stream() // .stream()
.map(CloudExpansion::getName) // .map(CloudExpansion::getName)
.map(name -> name.replace(' ', '_')); // .map(name -> name.replace(' ', '_'));
//
suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); // suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0));
} // }
} }

View File

@@ -20,12 +20,13 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import java.awt.*;
import java.util.List; import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -39,10 +40,11 @@ public final class CommandECloudRefresh extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
plugin.getCloudExpansionManager().load(); plugin.cloudExpansionManager().load();
Msg.msg(sender, sender.sendMessage(Message.raw("The eCloud manager has been refreshed!").color(Color.GREEN));
"&aThe eCloud manager has been refreshed!"); // Msg.msg(sender,
// "&aThe eCloud manager has been refreshed!");
} }
} }

View File

@@ -25,8 +25,8 @@ import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.manager.CloudExpansionManager; import at.helpch.placeholderapi.expansion.manager.CloudExpansionManager;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -40,7 +40,7 @@ public final class CommandECloudStatus extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
final CloudExpansionManager manager = plugin.getCloudExpansionManager(); final CloudExpansionManager manager = plugin.cloudExpansionManager();
final int updateCount = manager.getCloudUpdateCount(); final int updateCount = manager.getCloudUpdateCount();
final int authorCount = manager.getCloudExpansionAuthorCount(); final int authorCount = manager.getCloudExpansionAuthorCount();
@@ -59,7 +59,8 @@ public final class CommandECloudStatus extends PlaceholderCommand {
.append(updateCount > 1 ? "have an" : "has an").append(" update available."); .append(updateCount > 1 ? "have an" : "has an").append(" update available.");
} }
Msg.msg(sender, builder.toString()); sender.sendMessage(Message.raw(builder.toString()));
// Msg.msg(sender, builder.toString());
} }
} }

View File

@@ -20,11 +20,9 @@
package at.helpch.placeholderapi.commands.impl.cloud; package at.helpch.placeholderapi.commands.impl.cloud;
import com.google.common.collect.Lists; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -35,8 +33,8 @@ import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Futures; import at.helpch.placeholderapi.util.Futures;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -53,9 +51,9 @@ public final class CommandECloudUpdate extends PlaceholderCommand {
private static CompletableFuture<List<@Nullable Class<? extends PlaceholderExpansion>>> downloadAndDiscover( private static CompletableFuture<List<@Nullable Class<? extends PlaceholderExpansion>>> downloadAndDiscover(
@NotNull final List<CloudExpansion> expansions, @NotNull final PlaceholderAPIPlugin plugin) { @NotNull final List<CloudExpansion> expansions, @NotNull final PlaceholderAPIPlugin plugin) {
return expansions.stream() return expansions.stream()
.map(expansion -> plugin.getCloudExpansionManager() .map(expansion -> plugin.cloudExpansionManager()
.downloadExpansion(expansion, expansion.getVersion())) .downloadExpansion(expansion, expansion.getVersion()))
.map(future -> future.thenCompose(plugin.getLocalExpansionManager()::findExpansionInFile)) .map(future -> future.thenCompose(plugin.localExpansionManager()::findExpansionInFile))
.collect(Futures.collector()); .collect(Futures.collector());
} }
@@ -64,8 +62,9 @@ public final class CommandECloudUpdate extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must define 'all' or the name of an expansion to update.").color(Color.RED));
"&cYou must define 'all' or the name of an expansion to update."); // Msg.msg(sender,
// "&cYou must define 'all' or the name of an expansion to update.");
return; return;
} }
@@ -74,9 +73,9 @@ public final class CommandECloudUpdate extends PlaceholderCommand {
// gather target expansions // gather target expansions
if (multiple) { if (multiple) {
expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); expansions.addAll(plugin.cloudExpansionManager().getCloudExpansionsInstalled().values());
} else { } else {
plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)) plugin.cloudExpansionManager().findCloudExpansionByName(params.get(0))
.ifPresent(expansions::add); .ifPresent(expansions::add);
} }
@@ -84,60 +83,65 @@ public final class CommandECloudUpdate extends PlaceholderCommand {
expansions.removeIf(expansion -> !expansion.shouldUpdate()); expansions.removeIf(expansion -> !expansion.shouldUpdate());
if (expansions.isEmpty()) { if (expansions.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("No updates available for " + (!multiple ? "this expansion." : "your active expansions.")).color(Color.RED));
"&cNo updates available for " + (!multiple ? "this expansion." // Msg.msg(sender,
: "your active expansions.")); // "&cNo updates available for " + (!multiple ? "this expansion."
// : "your active expansions."));
return; return;
} }
Msg.msg(sender, sender.sendMessage(Message.raw("Updating expansions: " + expansions.stream().map(CloudExpansion::getName).collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))).color(Color.GREEN));
"&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) // Msg.msg(sender,
.collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); // "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName)
// .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r")));
Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> {
if (exception != null) { if (exception != null) {
Msg.msg(sender, sender.sendMessage(Message.raw("Failed to update expansions: ").color(Color.RED).insert(Message.raw(exception.getMessage()).color(Color.YELLOW)));
"&cFailed to update expansions: &e" + exception.getMessage()); // Msg.msg(sender,
// "&cFailed to update expansions: &e" + exception.getMessage());
return; return;
} }
Msg.msg(sender, sender.sendMessage(Message.raw("Successfully downloaded updates, registering new versions.").color(Color.GREEN));
"&aSuccessfully downloaded updates, registering new versions."); // Msg.msg(sender,
// "&aSuccessfully downloaded updates, registering new versions.");
final String message = classes.stream() final String message = classes.stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)
.map(plugin.getLocalExpansionManager()::register) .map(plugin.localExpansionManager()::register)
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion()) .map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion())
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
Msg.msg(sender, sender.sendMessage(Message.raw("&7Registered expansions: \n" + message));
"&7Registered expansions:", message); // Msg.msg(sender,
// "&7Registered expansions:", message);
}); });
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) { // if (params.size() > 1) {
return; // return;
} // }
//
final List<CloudExpansion> installed = Lists // final List<CloudExpansion> installed = Lists
.newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); // .newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values());
installed.removeIf(expansion -> !expansion.shouldUpdate()); // installed.removeIf(expansion -> !expansion.shouldUpdate());
//
if (!installed.isEmpty() && (params.isEmpty() || "all" // if (!installed.isEmpty() && (params.isEmpty() || "all"
.startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { // .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) {
suggestions.add("all"); // suggestions.add("all");
} // }
//
suggestByParameter( // suggestByParameter(
installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), // installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")),
suggestions, params.isEmpty() ? null : params.get(0)); // suggestions, params.isEmpty() ? null : params.get(0));
} // }
} }

View File

@@ -20,19 +20,16 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import at.helpch.placeholderapi.PlaceholderAPIBootstrap; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.util.Msg;
import com.hypixel.hytale.common.plugin.AuthorInfo; import com.hypixel.hytale.common.plugin.AuthorInfo;
import com.hypixel.hytale.common.util.java.ManifestUtil; import com.hypixel.hytale.common.util.java.ManifestUtil;
import com.hypixel.hytale.server.core.HytaleServer; import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.Message; import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.plugin.PluginBase; import com.hypixel.hytale.server.core.plugin.PluginBase;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -46,13 +43,11 @@ import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle; import java.time.format.FormatStyle;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public final class CommandDump extends PlaceholderCommand { public final class CommandDump extends PlaceholderCommand {
@@ -75,7 +70,7 @@ public final class CommandDump extends PlaceholderCommand {
} }
@Override @Override
public void evaluate(@NotNull final PlaceholderAPIBootstrap plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
postDump(makeDump(plugin)).whenComplete((key, exception) -> { postDump(makeDump(plugin)).whenComplete((key, exception) -> {
@@ -121,7 +116,7 @@ public final class CommandDump extends PlaceholderCommand {
} }
@NotNull @NotNull
private String makeDump(@NotNull final PlaceholderAPIBootstrap plugin) { private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append("Generated: ") builder.append("Generated: ")

View File

@@ -22,18 +22,14 @@ package at.helpch.placeholderapi.commands.impl.local;
import java.awt.*; import java.awt.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.logging.Level;
import at.helpch.placeholderapi.PlaceholderAPIBootstrap;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager; import at.helpch.placeholderapi.expansion.manager.LocalExpansionManager;
import at.helpch.placeholderapi.util.Futures; import at.helpch.placeholderapi.util.Futures;
import at.helpch.placeholderapi.util.Msg;
import com.hypixel.hytale.server.core.Message; import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -46,7 +42,7 @@ public final class CommandExpansionRegister extends PlaceholderCommand {
} }
@Override @Override
public void evaluate(@NotNull final PlaceholderAPIBootstrap plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
@@ -86,34 +82,35 @@ public final class CommandExpansionRegister extends PlaceholderCommand {
final Optional<PlaceholderExpansion> expansion = manager.register(clazz); final Optional<PlaceholderExpansion> expansion = manager.register(clazz);
if (!expansion.isPresent()) { if (!expansion.isPresent()) {
sender.sendMessage(Message.raw("Failed to register expansion from ").color(Color.RED).insert(Message.raw(params.getFirst()).color(Color.WHITE)));
// Msg.msg(sender, // Msg.msg(sender,
// "&cFailed to register expansion from &f" + params.get(0)); // "&cFailed to register expansion from &f" + params.get(0));
return; return;
} }
Msg.msg(sender, sender.sendMessage(Message.raw("Sucessfully registered expansion: ").color(Color.GREEN).insert(Message.raw(expansion.get().getName()).color(Color.WHITE)));
"&aSuccessfully registered expansion: &f" + expansion.get().getName()); // Msg.msg(sender,
// "&aSuccessfully registered expansion: &f" + expansion.get().getName());
}); });
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) { // if (params.size() > 1) {
return; // return;
} // }
//
final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() // final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder()
.list((dir, name) -> name.endsWith(".jar")); // .list((dir, name) -> name.endsWith(".jar"));
if (fileNames == null || fileNames.length == 0) { // if (fileNames == null || fileNames.length == 0) {
return; // return;
} // }
//
suggestByParameter(Arrays.stream(fileNames), suggestions, // suggestByParameter(Arrays.stream(fileNames), suggestions,
params.isEmpty() ? null : params.get(0)); // params.isEmpty() ? null : params.get(0));
} // }
} }

View File

@@ -20,15 +20,15 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import java.awt.*;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import at.helpch.placeholderapi.PlaceholderAPI;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -43,36 +43,43 @@ public final class CommandExpansionUnregister extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must specify the name of the expansion.").color(Color.RED));
"&cYou must specify the name of the expansion."); // Msg.msg(sender,
// "&cYou must specify the name of the expansion.");
return; return;
} }
final Optional<PlaceholderExpansion> expansion = plugin.getLocalExpansionManager() final Optional<PlaceholderExpansion> expansion = plugin.localExpansionManager()
.findExpansionByName(params.get(0)); .findExpansionByName(params.get(0));
if (!expansion.isPresent()) { if (!expansion.isPresent()) {
Msg.msg(sender, sender.sendMessage(Message.raw("There is no expansion loaded with the identifier: ").color(Color.RED).insert(Message.raw(params.getFirst()).color(Color.WHITE)));
"&cThere is no expansion loaded with the identifier: &f" + params.get(0)); // Msg.msg(sender,
// "&cThere is no expansion loaded with the identifier: &f" + params.get(0));
return; return;
} }
final String message = !expansion.get().unregister() ? // final String message = !expansion.get().unregister() ?
"&cFailed to unregister expansion: &f" : // "&cFailed to unregister expansion: &f" :
"&aSuccessfully unregistered expansion: &f"; // "&aSuccessfully unregistered expansion: &f";
final Message message = !expansion.get().unregister() ?
Message.raw("Failed to unregister expansion: ").color(Color.RED) :
Message.raw("Successfully unregistered expansion: ").color(Color.GREEN);
Msg.msg(sender, message + expansion.get().getName()); sender.sendMessage(message.insert(Message.raw(expansion.get().getName()).color(Color.WHITE)));
// sender.sendMessage(Message.raw(message + exp));
// Msg.msg(sender, message + expansion.get().getName());
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) { // if (params.size() > 1) {
return; // return;
} // }
//
suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, // suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions,
params.isEmpty() ? null : params.get(0)); // params.isEmpty() ? null : params.get(0));
} // }
} }

View File

@@ -20,14 +20,16 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import java.awt.*;
import java.util.List; import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.common.plugin.PluginManifest;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.Message;
import org.bukkit.plugin.PluginDescriptionFile; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
public final class CommandHelp extends PlaceholderCommand { public final class CommandHelp extends PlaceholderCommand {
@@ -41,33 +43,69 @@ public final class CommandHelp extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
final PluginDescriptionFile description = plugin.getDescription(); final PluginManifest description = plugin.getManifest();
// final PluginDescriptionFile description = plugin.getDescription();
Msg.msg(sender, final Message message = Message.raw("PlaceholderAPI ").color(Color.CYAN).bold(true)
"&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)", .insert(Message.raw("- ").color(Color.DARK_GRAY).bold(false))
" ", .insert(Message.raw("Help Menu ").color(Color.GRAY).bold(false))
"&b/papi &fbcparse &9<me|--null|player name> <message>", .insert(Message.raw("- ").color(Color.DARK_GRAY).bold(false))
" &7&oParse a message with placeholders and broadcast it", .insert(Message.raw("(").color(Color.GRAY).bold(false))
"&b/papi &fcmdparse &9<me|player> <command with placeholders>", .insert(Message.raw(description.getVersion().toString()).color(Color.WHITE).bold(false))
" &7&oParse a message with relational placeholders", .insert(Message.raw(")").color(Color.GRAY).bold(false))
"&b/papi &fdump", .insert(Message.raw("\n"))
" &7&oDump all relevant information needed to help debug issues into a paste link.", .insert(genCommandMsg("bcparse", "<me|--null|player name> <message>", "Parse a message with placeholders and broadcast it"))
"&b/papi &finfo &9<placeholder name>", .insert(genCommandMsg("cmdparse", "<me|player> <command with placeholders>", "Parse a message with relational placeholders"))
" &7&oView information for a specific expansion", .insert(genCommandMsg("dump", null, "Dump all relevant information needed to help debug issues into a paste link."))
"&b/papi &flist", .insert(genCommandMsg("info", "<placeholder name>", "View information for a specific expansion"))
" &7&oList active expansions", .insert(genCommandMsg("list", null, "List active expansions"))
"&b/papi &fparse &9<me|--null|player name> <message>", .insert(genCommandMsg("parse", "<me|--null|player name> <message>", "Parse a message with placeholders"))
" &7&oParse a message with placeholders", .insert(genCommandMsg("parserel", "<player one> <player two> <message>", "Parse a message with relational placeholders"))
"&b/papi &fparserel &9<player one> <player two> <message>", .insert(genCommandMsg("register", "<file name>", "Register an expansion by the name of the file"))
" &7&oParse a message with relational placeholders", .insert(genCommandMsg("reload", null, "Reload the config of PAPI"))
"&b/papi &fregister &9<file name>", .insert(genCommandMsg("unregister", "<expansion name>", "Unregister an expansion by name"))
" &7&oRegister an expansion by the name of the file", .insert(genCommandMsg("version", null, "View plugin info/version"));
"&b/papi &freload",
" &7&oReload the config of PAPI", sender.sendMessage(message);
"&b/papi &funregister &9<expansion name>",
" &7&oUnregister an expansion by name",
"&b/papi &fversion", // Msg.msg(sender,
" &7&oView plugin info/version"); // "&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)",
// " ",
// "&b/papi &fbcparse &9<me|--null|player name> <message>",
// " &7&oParse a message with placeholders and broadcast it",
// "&b/papi &fcmdparse &9<me|player> <command with placeholders>",
// " &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<placeholder name>",
// " &7&oView information for a specific expansion",
// "&b/papi &flist",
// " &7&oList active expansions",
// "&b/papi &fparse &9<me|--null|player name> <message>",
// " &7&oParse a message with placeholders",
// "&b/papi &fparserel &9<player one> <player two> <message>",
// " &7&oParse a message with relational placeholders",
// "&b/papi &fregister &9<file name>",
// " &7&oRegister an expansion by the name of the file",
// "&b/papi &freload",
// " &7&oReload the config of PAPI",
// "&b/papi &funregister &9<expansion name>",
// " &7&oUnregister an expansion by name",
// "&b/papi &fversion",
// " &7&oView plugin info/version");
} }
private Message genCommandMsg(@NotNull final String command, @Nullable final String arguments,
@NotNull final String description) {
Message message = Message.raw("\n/papi ").color(Color.CYAN)
.insert(Message.raw(command).color(Color.WHITE));
if (arguments != null) {
message = message.insert(" " + arguments).color(Color.BLUE);
}
return message
.insert(Message.raw("\n " + description).color(Color.GRAY).italic(true));
}
} }

View File

@@ -20,14 +20,14 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import java.awt.*;
import java.util.List; import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPI;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -42,73 +42,88 @@ public final class CommandInfo extends PlaceholderCommand {
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) { if (params.isEmpty()) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must specify the name of the expansion.").color(Color.RED));
"&cYou must specify the name of the expansion."); // Msg.msg(sender,
// "&cYou must specify the name of the expansion.");
return; return;
} }
final PlaceholderExpansion expansion = plugin.getLocalExpansionManager() final PlaceholderExpansion expansion = plugin.localExpansionManager()
.findExpansionByIdentifier(params.get(0)).orElse(null); .findExpansionByIdentifier(params.get(0)).orElse(null);
if (expansion == null) { if (expansion == null) {
Msg.msg(sender, sender.sendMessage(Message.raw("There is no expansion loaded with the identifier: ").color(Color.RED).insert(Message.raw(params.getFirst()).color(Color.WHITE)));
"&cThere is no expansion loaded with the identifier: &f" + params.get(0)); // Msg.msg(sender,
// "&cThere is no expansion loaded with the identifier: &f" + params.get(0));
return; return;
} }
final StringBuilder builder = new StringBuilder(); Message message = Message.empty()
.insert(Message.raw("Placeholder expansion info for: &r").color(Color.GRAY))
builder.append("&7Placeholder expansion info for: &r") .insert(Message.raw(expansion.getName() + "\n").color(Color.WHITE))
.append(expansion.getName()) .insert(Message.raw("Status: ").color(Color.GRAY))
.append('\n') .insert(Message.raw(expansion.isRegistered() ? "Registered" : "Not Registered").color(expansion.isRegistered() ? Color.GRAY : Color.RED))
.append("&7Status: &r") .insert("\n");
.append(expansion.isRegistered() ? "&aRegistered" : "7cNotRegistered")
.append('\n');
final String author = expansion.getAuthor(); final String author = expansion.getAuthor();
if (author != null) { if (author != null) {
builder.append("&7Author: &r") message = message.insert(Message.raw("Author: ").color(Color.GRAY))
.append(author) .insert(Message.raw(author + "\n").color(Color.WHITE));
.append('\n'); // builder.append("&7Author: &r")
// .append(author)
// .append('\n');
} }
final String version = expansion.getVersion(); final String version = expansion.getVersion();
if (version != null) { if (version != null) {
builder.append("&7Version: &r") message = message.insert(Message.raw("Version: ").color(Color.GRAY))
.append(version) .insert(Message.raw(version + "\n").color(Color.WHITE));
.append('\n');
// builder.append("&7Version: &r")
// .append(version)
// .append('\n');
} }
final String requiredPlugin = expansion.getRequiredPlugin(); final String requiredPlugin = expansion.getRequiredPlugin();
if (requiredPlugin != null) { if (requiredPlugin != null) {
builder.append("&7Requires plugin: &r") message = message.insert(Message.raw("Requires plugin: ").color(Color.GRAY))
.append(requiredPlugin) .insert(Message.raw(requiredPlugin + '\n').color(Color.WHITE));
.append('\n');
// builder.append("&7Requires plugin: &r")
// .append(requiredPlugin)
// .append('\n');
} }
final List<String> placeholders = expansion.getPlaceholders(); final List<String> placeholders = expansion.getPlaceholders();
if (placeholders != null && !placeholders.isEmpty()) { if (placeholders != null && !placeholders.isEmpty()) {
builder.append("&8&m-- &7Placeholders &8&m--&r") message = message.insert(Message.raw("-- ").color(Color.DARK_GRAY))
.append('\n'); .insert(Message.raw("Placeholders ").color(Color.GRAY))
.insert(Message.raw("--\n").color(Color.DARK_GRAY));
// builder.append("&8&m-- &7Placeholders &8&m--&r")
// .append('\n');
for (final String placeholder : placeholders) { for (final String placeholder : placeholders) {
builder.append(placeholder) message = message.insert(Message.raw(placeholder + "\n").color(Color.WHITE));
.append('\n'); // builder.append(placeholder)
// .append('\n');
} }
} }
Msg.msg(sender, builder.toString()); sender.sendMessage(message);
// Msg.msg(sender, builder.toString());
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) { // if (params.size() > 1) {
return; // return;
} // }
//
suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, // suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions,
params.isEmpty() ? null : params.get(0)); // params.isEmpty() ? null : params.get(0));
} // }
} }

View File

@@ -20,17 +20,17 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import com.google.common.collect.Lists; import java.awt.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream;
import at.helpch.placeholderapi.PlaceholderAPI; import at.helpch.placeholderapi.PlaceholderAPI;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -45,19 +45,44 @@ public final class CommandList extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
final Set<String> identifiers = PlaceholderAPI.getRegisteredIdentifiers(); final List<String> identifiers = new ArrayList<>(PlaceholderAPI.getRegisteredIdentifiers());
if (identifiers.isEmpty()) { if (identifiers.isEmpty()) {
Msg.msg(sender, "&cThere are no placeholder hooks active!"); sender.sendMessage(Message.raw("There are no placeholder hooks active!").color(Color.RED));
// Msg.msg(sender, "&cThere are no placeholder hooks active!");
return; return;
} }
final List<List<String>> partitions = Lists
.partition(identifiers.stream().sorted().collect(Collectors.toList()), 10);
Msg.msg(sender, final List<List<String>> partitions = new ArrayList<>(IntStream.range(0, identifiers.size()).boxed().collect(Collectors.groupingBy(i -> i/10, Collectors.mapping(identifiers::get, Collectors.toList()))).values());
"&7A total of &f" + identifiers.size() + "&7 placeholder hook(s) are active: &a", // final List<List<String>> partitions = Lists
partitions.stream().map(partition -> String.join("&7, &a", partition)) // .partition(identifiers.stream().sorted().collect(Collectors.toList()), 10);
.collect(Collectors.joining("\n")));
Message message = Message.raw("A total of ").color(Color.GRAY)
.insert(Message.raw(identifiers.size() + " ").color(Color.WHITE))
.insert(Message.raw("placeholder hook(s) are active: ").color(Color.GRAY));
for (int i = 0; i < partitions.size(); ++i) {
final List<String> partition = partitions.get(i);
for (int j = 0; j < partition.size(); ++j) {
message = message.insert(Message.raw(partition.get(j)).color(Color.GREEN));
if (j != partition.size() - 1) {
message = message.insert(Message.raw(", ").color(Color.GRAY));
}
}
if (i != partitions.size() - 1) {
message = message.insert(Message.raw("\n"));
}
}
sender.sendMessage(message);
// 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")));
} }
} }

View File

@@ -20,21 +20,21 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import java.util.HashSet; import java.awt.*;
import java.util.*;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPI; import at.helpch.placeholderapi.PlaceholderAPI;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.server.core.Message;
import org.bukkit.Bukkit; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.bukkit.OfflinePlayer; import com.hypixel.hytale.server.core.entity.entities.Player;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.server.core.universe.PlayerRef;
import org.bukkit.entity.Player; import com.hypixel.hytale.server.core.universe.Universe;
import com.hypixel.hytale.server.core.universe.world.World;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -66,39 +66,45 @@ public final class CommandParse extends PlaceholderCommand {
} }
} }
@Override // @Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, // public void complete(@NotNull final PlaceholderAPIBootstrap plugin,
@NotNull final CommandSender sender, @NotNull final String alias, // @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) { // @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
switch (alias.toLowerCase(Locale.ROOT)) { // switch (alias.toLowerCase(Locale.ROOT)) {
case "parserel": // case "parserel":
completeParseRelation(params, suggestions); // completeParseRelation(params, suggestions);
break; // break;
case "parse": // case "parse":
case "bcparse": // case "bcparse":
case "cmdparse": // case "cmdparse":
completeParseSingular(sender, params, suggestions); // completeParseSingular(sender, params, suggestions);
break; // break;
} // }
} // }
private void evaluateParseSingular(@NotNull final CommandSender sender, private void evaluateParseSingular(@NotNull final CommandSender sender,
@NotNull @Unmodifiable final List<String> params, final boolean broadcast, @NotNull @Unmodifiable final List<String> params, final boolean broadcast,
final boolean command) { final boolean command) {
if (params.size() < 2) { if (params.size() < 2) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must provide a target and a message: ").color(Color.RED)
"&cYou must provide a target and message: &b/papi " .insert(Message.raw("/papi ").color(Color.CYAN))
+ (command ? "cmdparse" : (broadcast ? "bcparse" : "parse")) .insert(Message.raw(command ? "cmdparse" : (broadcast ? "bcparse" : "parse")).color(Color.CYAN))
+ " &7{target} &a{message}"); .insert(Message.raw(" {target}").color(Color.GRAY))
.insert(Message.raw(" {message}").color(Color.GREEN)));
// Msg.msg(sender,
// "&cYou must provide a target and message: &b/papi "
// + (command ? "cmdparse" : (broadcast ? "bcparse" : "parse"))
// + " &7{target} &a{message}");
return; return;
} }
OfflinePlayer player; Player player;
if ("me".equalsIgnoreCase(params.get(0))) { if ("me".equalsIgnoreCase(params.get(0))) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); sender.sendMessage(Message.raw("You must be a player to use ").color(Color.RED).insert(Message.raw("me").color(Color.GRAY)).insert(Message.raw(" as a target!").color(Color.RED)));
// Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!");
return; return;
} }
@@ -106,9 +112,10 @@ public final class CommandParse extends PlaceholderCommand {
} else if ("--null".equalsIgnoreCase(params.get(0))) { } else if ("--null".equalsIgnoreCase(params.get(0))) {
player = null; player = null;
} else { } else {
final OfflinePlayer target = resolvePlayer(params.get(0)); final Player target = resolvePlayer(params.get(0), sender instanceof Player ? ((Player) sender).getWorld() : Universe.get().getDefaultWorld());
if (target == null) { if (target == null) {
Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); sender.sendMessage(Message.raw("Failed to find player: ").color(Color.RED).insert(Message.raw(params.get(0)).color(Color.WHITE)));
// Msg.msg(sender, "&cFailed to find player: &7" + params.get(0));
return; return;
} }
@@ -119,59 +126,71 @@ public final class CommandParse extends PlaceholderCommand {
.setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); .setPlaceholders(player, String.join(" ", params.subList(1, params.size())));
if (command) { if (command) {
Bukkit.dispatchCommand(sender, message); sender.sendMessage(Message.raw("To be implemented")); // todo: implement
// Bukkit.dispatchCommand(sender, message);
return; return;
} }
if (broadcast) { if (broadcast) {
Bukkit.broadcastMessage(message); Universe.get().sendMessage(Message.raw(message));
// Bukkit.broadcastMessage(message);
} else { } else {
sender.sendMessage(message); sender.sendMessage(Message.raw(message));
} }
} }
private void evaluateParseRelation(@NotNull final CommandSender sender, private void evaluateParseRelation(@NotNull final CommandSender sender,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (params.size() < 3) { if (params.size() < 3) {
Msg.msg(sender, sender.sendMessage(Message.raw("You must supply two targets, and a message: ").color(Color.RED)
"&cYou must supply two targets, and a message: &b/papi parserel &7{target one} " .insert(Message.raw("/papi parserel ").color(Color.CYAN))
+ "{target two} &a{message}"); .insert(Message.raw("{target one} {target two} ").color(Color.GRAY))
.insert(Message.raw("{message}").color(Color.GREEN)));
// Msg.msg(sender,
// "&cYou must supply two targets, and a message: &b/papi parserel &7{target one} "
// + "{target two} &a{message}");
return; return;
} }
OfflinePlayer playerOne; Player playerOne;
if ("me".equalsIgnoreCase(params.get(0))) { if ("me".equalsIgnoreCase(params.get(0))) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); sender.sendMessage(Message.raw("You must be a player to use ").color(Color.RED)
.insert(Message.raw("me").color(Color.GRAY))
.insert(Message.raw(" as a target!").color(Color.RED)));
// Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!");
return; return;
} }
playerOne = ((Player) sender); playerOne = ((Player) sender);
} else { } else {
playerOne = resolvePlayer(params.get(0)); playerOne = resolvePlayer(params.get(0), sender instanceof Player ? ((Player) sender).getWorld() : Universe.get().getDefaultWorld());
} }
if (playerOne == null || !playerOne.isOnline()) { if (playerOne == null/* || !playerOne.isOnline()*/) {
Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); sender.sendMessage(Message.raw("Failed to find player: ").color(Color.RED).insert(Message.raw(params.get(0)).color(Color.WHITE)));
// Msg.msg(sender, "&cFailed to find player: &f" + params.get(0));
return; return;
} }
OfflinePlayer playerTwo; Player playerTwo;
if ("me".equalsIgnoreCase(params.get(1))) { if ("me".equalsIgnoreCase(params.get(1))) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); sender.sendMessage(Message.raw("You must be a player to use ").color(Color.RED).insert(Message.raw("me").color(Color.GRAY)).insert(Message.raw(" as a target!").color(Color.RED)));
// Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!");
return; return;
} }
playerTwo = ((Player) sender); playerTwo = ((Player) sender);
} else { } else {
playerTwo = resolvePlayer(params.get(1)); playerTwo = resolvePlayer(params.get(1), sender instanceof Player ? ((Player) sender).getWorld() : Universe.get().getDefaultWorld());
} }
if (playerTwo == null || !playerTwo.isOnline()) { if (playerTwo == null/* || !playerTwo.isOnline()*/) {
Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); sender.sendMessage(Message.raw("Failed to find player: ").color(Color.RED).insert(Message.raw(params.get(1)).color(Color.WHITE)));
// Msg.msg(sender, "&cFailed to find player: &f" + params.get(1));
return; return;
} }
@@ -179,7 +198,7 @@ public final class CommandParse extends PlaceholderCommand {
.setRelationalPlaceholders((Player) playerOne, (Player) playerTwo, .setRelationalPlaceholders((Player) playerOne, (Player) playerTwo,
String.join(" ", params.subList(2, params.size()))); String.join(" ", params.subList(2, params.size())));
sender.sendMessage(message); sender.sendMessage(Message.raw(message));
} }
@@ -195,7 +214,8 @@ public final class CommandParse extends PlaceholderCommand {
suggestions.add("--null"); suggestions.add("--null");
} }
final Stream<String> names = Bukkit.getOnlinePlayers().stream().map(Player::getName); final Stream<String> names = Universe.get().getPlayers().stream().map(PlayerRef::getUsername);
// final Stream<String> names = Bukkit.getOnlinePlayers().stream().map(Player::getName);
suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0));
return; return;
@@ -211,8 +231,8 @@ public final class CommandParse extends PlaceholderCommand {
return; // no arguments supplied yet return; // no arguments supplied yet
} }
final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() final PlaceholderExpansion expansion = PlaceholderAPIPlugin.instance()
.getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) .localExpansionManager().findExpansionByIdentifier(name.substring(1, index))
.orElse(null); .orElse(null);
if (expansion == null) { if (expansion == null) {
return; return;
@@ -220,37 +240,39 @@ public final class CommandParse extends PlaceholderCommand {
final Set<String> possible = new HashSet<>(expansion.getPlaceholders()); final Set<String> possible = new HashSet<>(expansion.getPlaceholders());
PlaceholderAPIPlugin.getInstance() PlaceholderAPIPlugin.instance()
.getCloudExpansionManager() .cloudExpansionManager()
.findCloudExpansionByName(expansion.getName()) .findCloudExpansionByName(expansion.getName())
.ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders()));
suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1));
} }
private void completeParseRelation(@NotNull @Unmodifiable final List<String> params, // private void completeParseRelation(@NotNull @Unmodifiable final List<String> params,
@NotNull final List<String> suggestions) { // @NotNull final List<String> suggestions) {
if (params.size() > 2) { // if (params.size() > 2) {
return; // return;
} // }
//
final Stream<String> names = Bukkit.getOnlinePlayers().stream().map(Player::getName); // final Stream<String> names = Bukkit.getOnlinePlayers().stream().map(Player::getName);
suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1)); // suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1));
} // }
@Nullable @Nullable
private OfflinePlayer resolvePlayer(@NotNull final String name) { private Player resolvePlayer(@NotNull final String name, @NotNull final World world) {
OfflinePlayer target = Bukkit.getPlayerExact(name); // Player target = Universe.get().getPlayerByUsername(name, NameMatching.EXACT);
final Optional<Player> target = world.getPlayers().stream().filter(player -> player.getDisplayName().equals(name)).findAny();
if (target == null) { if (target.isEmpty()) {
// Not the best option, but Spigot doesn't offer a good replacement (as usual) // Not the best option, but Spigot doesn't offer a good replacement (as usual)
target = Bukkit.getOfflinePlayer(name); // target = Bukkit.getOfflinePlayer(name);
//
return target.hasPlayedBefore() ? target : null; // return target.hasPlayedBefore() ? target : null;
return null;
} }
return target; return target.get();
} }

View File

@@ -24,8 +24,7 @@ import java.util.List;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.ExpansionSafetyCheck; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -39,9 +38,7 @@ public final class CommandReload extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
if (!new ExpansionSafetyCheck(plugin).runChecks()) { plugin.reloadPlugin(sender);
plugin.reloadConf(sender);
}
} }
} }

View File

@@ -20,13 +20,16 @@
package at.helpch.placeholderapi.commands.impl.local; package at.helpch.placeholderapi.commands.impl.local;
import java.awt.*;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.commands.PlaceholderCommand; import at.helpch.placeholderapi.commands.PlaceholderCommand;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.common.plugin.AuthorInfo;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.common.plugin.PluginManifest;
import org.bukkit.plugin.PluginDescriptionFile; import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
@@ -41,13 +44,27 @@ public final class CommandVersion extends PlaceholderCommand {
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias, @NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) { @NotNull @Unmodifiable final List<String> params) {
final PluginDescriptionFile description = plugin.getDescription(); final PluginManifest description = plugin.getManifest();
Msg.msg(sender, sender.sendMessage(Message.empty()
"&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)", .insert(Message.raw("PlaceholderAPI ").color(Color.CYAN).bold(true))
"&7Author: &f" + description.getAuthors(), .insert(Message.raw("(").color(Color.GRAY))
"&7PAPI Commands: &b/papi &fhelp", .insert(Message.raw(description.getVersion().toString()).color(Color.WHITE))
"&7eCloud Commands&8: &b/papi &fecloud"); .insert(Message.raw(")").color(Color.GRAY))
.insert(Message.raw("\nAuthor: ").color(Color.GRAY))
.insert(Message.raw(description.getAuthors().stream().map(AuthorInfo::getName).collect(Collectors.joining(", "))).color(Color.WHITE))
.insert(Message.raw("\nPAPI Commands: ").color(Color.GRAY))
.insert(Message.raw("/papi ").color(Color.CYAN))
.insert(Message.raw("help").color(Color.WHITE))
.insert(Message.raw("\neCloud Commands: ").color(Color.GRAY))
.insert(Message.raw("/papi ").color(Color.CYAN))
.insert(Message.raw("ecloud").color(Color.WHITE)));
// Msg.msg(sender,
// "&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)",
// "&7Author: &f" + description.getAuthors().stream().map(AuthorInfo::getName).collect(Collectors.joining(", ")),
// "&7PAPI Commands: &b/papi &fhelp",
// "&7eCloud Commands&8: &b/papi &fecloud");
} }
} }

View File

@@ -1,6 +1,6 @@
package at.helpch.placeholderapi.configuration; package at.helpch.placeholderapi.configuration;
import at.helpch.placeholderapi.PlaceholderAPIBootstrap; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@@ -11,7 +11,6 @@ import org.jetbrains.annotations.Nullable;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@@ -63,6 +62,11 @@ public final class ConfigManager {
} }
@NotNull
public <T> T convertExpansion(@NotNull final Map<String, Object> expansionConfig, @NotNull final Class<T> type) {
return GSON.fromJson(GSON.toJsonTree(expansionConfig), type);
}
@Nullable @Nullable
private Path createFile(@NotNull final String internalPath, @NotNull final String externalPath) { private Path createFile(@NotNull final String internalPath, @NotNull final String externalPath) {
final Path file = Paths.get(externalPath); final Path file = Paths.get(externalPath);
@@ -94,7 +98,7 @@ public final class ConfigManager {
private boolean exportResource(@NotNull final String internalPath, @NotNull final String externalPath) { private boolean exportResource(@NotNull final String internalPath, @NotNull final String externalPath) {
try { try {
Files.copy(PlaceholderAPIBootstrap.class.getResourceAsStream(internalPath), Paths.get(externalPath), Files.copy(PlaceholderAPIPlugin.class.getResourceAsStream(internalPath), Paths.get(externalPath),
StandardCopyOption.REPLACE_EXISTING); StandardCopyOption.REPLACE_EXISTING);
return true; return true;

View File

@@ -22,8 +22,88 @@ package at.helpch.placeholderapi.configuration;
import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.JsonAdapter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public record PlaceholderAPIConfig(boolean cloudEnabled, boolean debugMode, @NotNull ExpansionSort cloudSorting, import java.util.HashMap;
@NotNull BooleanValue booleanValue, @NotNull String dateFormat) { import java.util.Map;
public final class PlaceholderAPIConfig {
private boolean cloudEnabled;
private boolean debugMode;
private ExpansionSort cloudSorting;
private BooleanValue booleanValue;
private String dateFormat;
private Map<String, Object> expansions;
public PlaceholderAPIConfig(boolean cloudEnabled, boolean debugMode, @NotNull ExpansionSort cloudSorting,
@NotNull BooleanValue booleanValue, @NotNull String dateFormat) {
this.cloudEnabled = cloudEnabled;
this.debugMode = debugMode;
this.cloudSorting = cloudSorting;
this.booleanValue = booleanValue;
this.dateFormat = dateFormat;
this.expansions = new HashMap<>();
}
public PlaceholderAPIConfig(boolean cloudEnabled, boolean debugMode, @NotNull ExpansionSort cloudSorting,
@NotNull BooleanValue booleanValue, @NotNull String dateFormat, Map<String, Object> expansions) {
this.cloudEnabled = cloudEnabled;
this.debugMode = debugMode;
this.cloudSorting = cloudSorting;
this.booleanValue = booleanValue;
this.dateFormat = dateFormat;
this.expansions = expansions;
}
public boolean cloudEnabled() {
return cloudEnabled;
}
public void cloudEnabled(final boolean value) {
cloudEnabled = value;
}
public boolean debugMode() {
return debugMode;
}
public void debugMode(final boolean value) {
debugMode = value;
}
@NotNull
public ExpansionSort cloudSorting() {
return cloudSorting;
}
public void cloudSorting(@NotNull final ExpansionSort value) {
cloudSorting = value;
}
@NotNull
public BooleanValue booleanValue() {
return booleanValue;
}
public void booleanValue(@NotNull final BooleanValue value) {
booleanValue = value;
}
@NotNull
public String dateFormat() {
return dateFormat;
}
public void dateFormat(@NotNull final String value) {
dateFormat = value;
}
@NotNull
public Map<String, Object> expansions() {
return expansions;
}
public void expansions(@NotNull final Map<String, Object> value) {
expansions = value;
}
} }

View File

@@ -21,9 +21,8 @@
package at.helpch.placeholderapi.events; package at.helpch.placeholderapi.events;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.event.Cancellable; import com.hypixel.hytale.event.ICancellable;
import org.bukkit.event.Event; import com.hypixel.hytale.event.IEvent;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@@ -33,10 +32,7 @@ import org.jetbrains.annotations.NotNull;
* <p>To know when <b>all</b> Expansions have been registered, use the * <p>To know when <b>all</b> Expansions have been registered, use the
* {@link at.helpch.placeholderapi.events.ExpansionsLoadedEvent ExpansionsLoadedEvent} instead. * {@link at.helpch.placeholderapi.events.ExpansionsLoadedEvent ExpansionsLoadedEvent} instead.
*/ */
public final class ExpansionRegisterEvent extends Event implements Cancellable { public final class ExpansionRegisterEvent implements IEvent<Void>, ICancellable {
@NotNull
private static final HandlerList HANDLERS = new HandlerList();
@NotNull @NotNull
private final PlaceholderExpansion expansion; private final PlaceholderExpansion expansion;
private boolean cancelled; private boolean cancelled;
@@ -45,11 +41,6 @@ public final class ExpansionRegisterEvent extends Event implements Cancellable {
this.expansion = expansion; this.expansion = expansion;
} }
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
/** /**
* The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI. * The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI.
* <br>The PlaceholderExpansion will be available for use when the event * <br>The PlaceholderExpansion will be available for use when the event
@@ -80,10 +71,4 @@ public final class ExpansionRegisterEvent extends Event implements Cancellable {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
} }

View File

@@ -21,8 +21,7 @@
package at.helpch.placeholderapi.events; package at.helpch.placeholderapi.events;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.event.Event; import com.hypixel.hytale.event.IEvent;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@@ -34,11 +33,7 @@ import org.jetbrains.annotations.NotNull;
* <br>This includes removing any Listeners, stopping active tasks and clearing the cache of * <br>This includes removing any Listeners, stopping active tasks and clearing the cache of
* the PlaceholderExpansion. * the PlaceholderExpansion.
*/ */
public final class ExpansionUnregisterEvent extends Event { public final class ExpansionUnregisterEvent implements IEvent<ExpansionUnregisterEvent> {
@NotNull
private static final HandlerList HANDLERS = new HandlerList();
@NotNull @NotNull
private final PlaceholderExpansion expansion; private final PlaceholderExpansion expansion;
@@ -46,11 +41,6 @@ public final class ExpansionUnregisterEvent extends Event {
this.expansion = expansion; this.expansion = expansion;
} }
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
/** /**
* The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered. * The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered.
* *
@@ -61,10 +51,4 @@ public final class ExpansionUnregisterEvent extends Event {
return expansion; return expansion;
} }
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
} }

View File

@@ -25,8 +25,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.event.Event; import com.hypixel.hytale.event.IEvent;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@@ -37,7 +36,7 @@ import org.jetbrains.annotations.NotNull;
* <p>All PlaceholderExpansions, except for those loaded by plugins, are loaded * <p>All PlaceholderExpansions, except for those loaded by plugins, are loaded
* after Spigot triggered its ServerLoadEvent (1.13+), or after PlaceholderAPI has been enabled. * after Spigot triggered its ServerLoadEvent (1.13+), or after PlaceholderAPI has been enabled.
*/ */
public class ExpansionsLoadedEvent extends Event { public class ExpansionsLoadedEvent implements IEvent<ExpansionsLoadedEvent> {
private final List<PlaceholderExpansion> expansions; private final List<PlaceholderExpansion> expansions;
@@ -57,18 +56,4 @@ public class ExpansionsLoadedEvent extends Event {
public final List<PlaceholderExpansion> getExpansions() { public final List<PlaceholderExpansion> getExpansions() {
return expansions; return expansions;
} }
@NotNull
private static final HandlerList HANDLERS = new HandlerList();
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
} }

View File

@@ -1,70 +0,0 @@
/*
* This file is part of PlaceholderAPI
*
* PlaceholderAPI
* Copyright (c) 2015 - 2026 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 <http://www.gnu.org/licenses/>.
*/
package at.helpch.placeholderapi.events;
import at.helpch.placeholderapi.PlaceholderHook;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated This event is no longer used.
*/
@Deprecated
public final class PlaceholderHookUnloadEvent extends Event {
@NotNull
private static final HandlerList HANDLERS = new HandlerList();
@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;
}
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
@NotNull
public String getHookName() {
return plugin;
}
@NotNull
public PlaceholderHook getHook() {
return placeholderHook;
}
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
}

View File

@@ -20,10 +20,10 @@
package at.helpch.placeholderapi.expansion; package at.helpch.placeholderapi.expansion;
import org.bukkit.entity.Player; import com.hypixel.hytale.server.core.universe.PlayerRef;
/** /**
* Classes implementing this interface will have a {@link #cleanup(Player) cleanup void} that is * Classes implementing this interface will have a {@link #cleanup(PlayerRef) cleanup void} that is
* called by PlaceholderAPI whenever a Player leaves the server. * called by PlaceholderAPI whenever a Player leaves the server.
* *
* <p>This can be useful for cases where you keep data of the player in a cache or similar * <p>This can be useful for cases where you keep data of the player in a cache or similar
@@ -38,5 +38,5 @@ public interface Cleanable {
* *
* @param p (@link Player} who left the server * @param p (@link Player} who left the server
*/ */
void cleanup(Player p); void cleanup(PlayerRef p);
} }

View File

@@ -20,6 +20,8 @@
package at.helpch.placeholderapi.expansion; package at.helpch.placeholderapi.expansion;
import org.jetbrains.annotations.NotNull;
import java.util.Map; import java.util.Map;
/** /**
@@ -41,17 +43,23 @@ import java.util.Map;
* *
* @author Ryan McCarthy * @author Ryan McCarthy
*/ */
public interface Configurable { public interface Configurable<T> {
/** @NotNull
* The map returned by this method will be used to set config options in PlaceholderAPI's config.yml. Class<T> provideConfigType();
*
* <p>The key and value pairs are set under a section named after your @NotNull
* {@link at.helpch.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} in the T provideDefault();
* {@code expansions} section of the config.
* // /**
* @return Map of config path / values which need to be added / removed from the PlaceholderAPI // * The map returned by this method will be used to set config options in PlaceholderAPI's config.yml.
* config.yml file // *
*/ // * <p>The key and value pairs are set under a section named after your
Map<String, Object> getDefaults(); // * {@link at.helpch.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<String, Object> getDefaults();
} }

View File

@@ -1,81 +0,0 @@
/*
* This file is part of PlaceholderAPI
*
* PlaceholderAPI
* Copyright (c) 2015 - 2026 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 <http://www.gnu.org/licenses/>.
*/
package at.helpch.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;
}
}

View File

@@ -21,15 +21,16 @@
package at.helpch.placeholderapi.expansion; package at.helpch.placeholderapi.expansion;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.PlaceholderHook; import at.helpch.placeholderapi.PlaceholderHook;
import org.bukkit.Bukkit; import com.hypixel.hytale.server.core.HytaleServer;
import org.bukkit.configuration.ConfigurationSection; import com.hypixel.hytale.server.core.plugin.PluginBase;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -124,7 +125,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* @return true if the identifier for this expansion is already registered * @return true if the identifier for this expansion is already registered
*/ */
public final boolean isRegistered() { public final boolean isRegistered() {
return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier()) return getPlaceholderAPI().localExpansionManager().findExpansionByIdentifier(getIdentifier())
.map(it -> it.equals(this)).orElse(false); .map(it -> it.equals(this)).orElse(false);
} }
@@ -137,7 +138,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
*/ */
public boolean canRegister() { public boolean canRegister() {
return getRequiredPlugin() == null return getRequiredPlugin() == null
|| Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null; || HytaleServer.get().getPluginManager().getPlugins().stream().map(PluginBase::getName).anyMatch(getRequiredPlugin()::equals);
} }
/** /**
@@ -146,7 +147,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* @return true if this expansion is now registered with PlaceholderAPI * @return true if this expansion is now registered with PlaceholderAPI
*/ */
public boolean register() { public boolean register() {
return getPlaceholderAPI().getLocalExpansionManager().register(this); return getPlaceholderAPI().localExpansionManager().register(this);
} }
/** /**
@@ -155,7 +156,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* @return true if this expansion is now unregistered with PlaceholderAPI * @return true if this expansion is now unregistered with PlaceholderAPI
*/ */
public final boolean unregister() { public final boolean unregister() {
return getPlaceholderAPI().getLocalExpansionManager().unregister(this); return getPlaceholderAPI().localExpansionManager().unregister(this);
} }
@@ -166,7 +167,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
*/ */
@NotNull @NotNull
public final PlaceholderAPIPlugin getPlaceholderAPI() { public final PlaceholderAPIPlugin getPlaceholderAPI() {
return PlaceholderAPIPlugin.getInstance(); return PlaceholderAPIPlugin.instance();
} }
/** /**
@@ -200,131 +201,136 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* *
* @return ConfigurationSection that this expansion has. * @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 @NotNull
public final List<String> getStringList(@NotNull final String path) { public final Map<String, Object> getExpansionConfig() {
final ConfigurationSection section = getConfigSection(); return (Map<String, Object>) getPlaceholderAPI().configManager().config().expansions().getOrDefault(getIdentifier(), new HashMap<>());
return section == null ? Collections.emptyList() : section.getStringList(path);
} }
/** @Nullable
* Gets the boolean relative to the {@link #getConfigSection() default ConfigurationSection} set public final <T> T getExpansionConfig(@NotNull final Class<? extends Configurable<T>> configurableType) {
* by the expansion or the default boolean, when the default ConfigurationSection is null return (T) getPlaceholderAPI().configManager().config().expansions().getOrDefault(getIdentifier(), 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 // * Gets the ConfigurationSection relative to the {@link #getConfigSection() default one} set
* or not. This will return {@code false} when either the default section is null, or doesn't // * by the expansion or null when the default ConfigurationSection is null
* contain the provided path // *
* // * @param path The path to get the ConfigurationSection from. This is relative to the default section
* @param path The path to check // * @return ConfigurationSection relative to the default section
* @return true when the default ConfigurationSection is not null and contains the path, false otherwise // */
*/ // @Nullable
public final boolean configurationContains(@NotNull final String path) { // public final ConfigurationSection getConfigSection(@NotNull final String path) {
final ConfigurationSection section = getConfigSection(); // final ConfigurationSection section = getConfigSection();
return section != null && section.contains(path); // 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<String> 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. * Logs the provided message with the provided Level in the console.
@@ -334,7 +340,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* @param msg The message to log * @param msg The message to log
*/ */
public void log(Level level, String msg) { public void log(Level level, String msg) {
getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg); getPlaceholderAPI().getLogger().at(level).log("[" + getName() + "] " + msg);
} }
/** /**
@@ -346,7 +352,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook {
* @param throwable The Throwable to log * @param throwable The Throwable to log
*/ */
public void log(Level level, String msg, Throwable throwable) { public void log(Level level, String msg, Throwable throwable) {
getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg, throwable); getPlaceholderAPI().getLogger().at(level).log("[" + getName() + "] " + msg, throwable);
} }
/** /**

View File

@@ -20,7 +20,7 @@
package at.helpch.placeholderapi.expansion; package at.helpch.placeholderapi.expansion;
import org.bukkit.entity.Player; import com.hypixel.hytale.server.core.entity.entities.Player;
/** /**
* Implementing this interface allows your {@link at.helpch.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} * Implementing this interface allows your {@link at.helpch.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion}

View File

@@ -20,17 +20,15 @@
package at.helpch.placeholderapi.expansion.manager; package at.helpch.placeholderapi.expansion.manager;
import com.google.common.collect.ImmutableMap; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import java.io.File; import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.URI;
import java.net.URL; import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -42,27 +40,23 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.*;
import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function; import java.util.function.Function;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collector; import java.util.stream.Collector;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.logger.HytaleLogger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.Unmodifiable;
public final class CloudExpansionManager { public final class CloudExpansionManager {
@NotNull @NotNull
private static final String API_URL = "https://ecloud.placeholderapi.com/api/v3/"; private static final String API_URL = "https://ecloud.placeholderapi.com/api/v3/?platform=hytale";
@NotNull @NotNull
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
@@ -76,6 +70,7 @@ public final class CloudExpansionManager {
@NotNull @NotNull
private final PlaceholderAPIPlugin plugin; private final PlaceholderAPIPlugin plugin;
private final HytaleLogger logger;
@NotNull @NotNull
private final Map<String, CloudExpansion> cache = new HashMap<>(); private final Map<String, CloudExpansion> cache = new HashMap<>();
@@ -83,11 +78,11 @@ public final class CloudExpansionManager {
private final Map<String, CompletableFuture<File>> await = new ConcurrentHashMap<>(); private final Map<String, CompletableFuture<File>> await = new ConcurrentHashMap<>();
private final ExecutorService ASYNC_EXECUTOR = private final ExecutorService ASYNC_EXECUTOR =
Executors.newCachedThreadPool( Executors.newCachedThreadPool(new LoggingThreadFactory("placeholderapi-io-#%1$d"));
new ThreadFactoryBuilder().setNameFormat("placeholderapi-io-#%1$d").build());
public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
this.logger = plugin.getLogger();
} }
@NotNull @NotNull
@@ -112,7 +107,7 @@ public final class CloudExpansionManager {
@NotNull @NotNull
@Unmodifiable @Unmodifiable
public Map<String, CloudExpansion> getCloudExpansions() { public Map<String, CloudExpansion> getCloudExpansions() {
return ImmutableMap.copyOf(cache); return Map.copyOf(cache);
} }
@NotNull @NotNull
@@ -152,7 +147,7 @@ public final class CloudExpansionManager {
} }
public int getCloudUpdateCount() { public int getCloudUpdateCount() {
return ((int) plugin.getLocalExpansionManager() return ((int) plugin.localExpansionManager()
.getExpansions() .getExpansions()
.stream() .stream()
.filter(expansion -> findCloudExpansionByName(expansion.getName()) .filter(expansion -> findCloudExpansionByName(expansion.getName())
@@ -173,15 +168,24 @@ public final class CloudExpansionManager {
} }
public void fetch() { public void fetch() {
plugin.getLogger().info("Fetching available expansion information..."); logger.at(Level.INFO).log("Fetching available expansion information...");
ASYNC_EXECUTOR.submit( ASYNC_EXECUTOR.submit(
() -> { () -> {
// a defence tactic! use ConcurrentHashMap instead of normal HashMap // a defence tactic! use ConcurrentHashMap instead of normal HashMap
Map<String, CloudExpansion> values = new ConcurrentHashMap<>(); Map<String, CloudExpansion> values = new ConcurrentHashMap<>();
try { try {
final URI uri = new URI(API_URL);
final URLConnection connection = uri.toURL().openConnection();
final String json;
try (final InputStream input = connection.getInputStream()) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
json = reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
//noinspection UnstableApiUsage //noinspection UnstableApiUsage
String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); // String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8);
values.putAll(GSON.fromJson(json, TYPE)); values.putAll(GSON.fromJson(json, TYPE));
List<String> toRemove = new ArrayList<>(); List<String> toRemove = new ArrayList<>();
@@ -199,13 +203,13 @@ public final class CloudExpansionManager {
} }
} catch (Throwable e) { } catch (Throwable e) {
// ugly swallowing of every throwable, but we have to be defensive // ugly swallowing of every throwable, but we have to be defensive
plugin.getLogger().log(Level.WARNING, "Failed to download expansion information", e); logger.atWarning().log("Failed to download expansion information", e);
} }
// loop through what's left on the main thread // loop through what's left on the main thread
plugin plugin
.getScheduler() .getTaskRegistry()
.runTask( .registerTask(CompletableFuture.runAsync(
() -> { () -> {
try { try {
for (Map.Entry<String, CloudExpansion> entry : values.entrySet()) { for (Map.Entry<String, CloudExpansion> entry : values.entrySet()) {
@@ -215,7 +219,7 @@ public final class CloudExpansionManager {
expansion.setName(name); expansion.setName(name);
Optional<PlaceholderExpansion> localOpt = Optional<PlaceholderExpansion> localOpt =
plugin.getLocalExpansionManager().findExpansionByName(name); plugin.localExpansionManager().findExpansionByName(name);
if (localOpt.isPresent()) { if (localOpt.isPresent()) {
PlaceholderExpansion local = localOpt.get(); PlaceholderExpansion local = localOpt.get();
if (local.isRegistered()) { if (local.isRegistered()) {
@@ -229,11 +233,9 @@ public final class CloudExpansionManager {
} }
} catch (Throwable e) { } catch (Throwable e) {
// ugly swallowing of every throwable, but we have to be defensive // ugly swallowing of every throwable, but we have to be defensive
plugin logger.atWarning().log("Failed to download expansion information", e);
.getLogger()
.log(Level.WARNING, "Failed to download expansion information", e);
} }
}); }));
}); });
} }
@@ -249,7 +251,7 @@ public final class CloudExpansionManager {
return previous; return previous;
} }
final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), final File file = new File(plugin.localExpansionManager().getExpansionsFolder(),
"Expansion-" + toIndexName(expansion) + ".jar"); "Expansion-" + toIndexName(expansion) + ".jar");
final CompletableFuture<File> download = CompletableFuture.supplyAsync(() -> { final CompletableFuture<File> download = CompletableFuture.supplyAsync(() -> {
@@ -266,7 +268,7 @@ public final class CloudExpansionManager {
await.remove(toIndexName(expansion)); await.remove(toIndexName(expansion));
if (exception != null) { if (exception != null) {
Msg.severe("Failed to download %s:%s", exception, expansion.getName(), expansion.getVersion()); logger.atSevere().log("Failed to download %s:%s %s", expansion.getName(), expansion.getVersion(), exception);
} }
}, ASYNC_EXECUTOR); }, ASYNC_EXECUTOR);
@@ -275,4 +277,20 @@ public final class CloudExpansionManager {
return download; return download;
} }
private static final class LoggingThreadFactory implements ThreadFactory {
private final ThreadFactory backing = Executors.defaultThreadFactory();
private final String format;
private final AtomicLong count = new AtomicLong(0);
private LoggingThreadFactory(@NotNull final String format) {
this.format = format;
}
@Override
public Thread newThread(@NotNull final Runnable r) {
final Thread thread = backing.newThread(r);
thread.setName(String.format(format, count.getAndIncrement()));
return thread;
}
}
} }

View File

@@ -20,28 +20,21 @@
package at.helpch.placeholderapi.expansion.manager; package at.helpch.placeholderapi.expansion.manager;
import at.helpch.placeholderapi.PlaceholderAPIBootstrap; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.awt.*;
import java.io.File; import java.io.File;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Arrays; import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List; 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.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.configuration.ConfigManager;
import at.helpch.placeholderapi.configuration.PlaceholderAPIConfig;
import at.helpch.placeholderapi.events.ExpansionRegisterEvent; import at.helpch.placeholderapi.events.ExpansionRegisterEvent;
import at.helpch.placeholderapi.events.ExpansionUnregisterEvent; import at.helpch.placeholderapi.events.ExpansionUnregisterEvent;
import at.helpch.placeholderapi.events.ExpansionsLoadedEvent; import at.helpch.placeholderapi.events.ExpansionsLoadedEvent;
@@ -53,16 +46,14 @@ import at.helpch.placeholderapi.expansion.Taskable;
import at.helpch.placeholderapi.expansion.cloud.CloudExpansion; import at.helpch.placeholderapi.expansion.cloud.CloudExpansion;
import at.helpch.placeholderapi.util.FileUtil; import at.helpch.placeholderapi.util.FileUtil;
import at.helpch.placeholderapi.util.Futures; import at.helpch.placeholderapi.util.Futures;
import at.helpch.placeholderapi.util.Msg; import com.hypixel.hytale.common.plugin.PluginIdentifier;
import org.bukkit.Bukkit; import com.hypixel.hytale.event.IEventDispatcher;
import org.bukkit.command.CommandSender; import com.hypixel.hytale.logger.HytaleLogger;
import org.bukkit.configuration.file.FileConfiguration; import com.hypixel.hytale.server.core.HytaleServer;
import org.bukkit.event.EventHandler; import com.hypixel.hytale.server.core.Message;
import org.bukkit.event.EventPriority; import com.hypixel.hytale.server.core.command.system.CommandSender;
import org.bukkit.event.HandlerList; import com.hypixel.hytale.server.core.event.events.player.PlayerDisconnectEvent;
import org.bukkit.event.Listener; import com.hypixel.hytale.server.core.plugin.PluginBase;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -83,18 +74,22 @@ public final class LocalExpansionManager /*implements Listener*/ {
private final File folder; private final File folder;
@NotNull @NotNull
private final PlaceholderAPIPlugin plugin; private final PlaceholderAPIPlugin plugin;
private final HytaleLogger logger;
private final ConfigManager configManager;
@NotNull @NotNull
private final Map<String, PlaceholderExpansion> expansions = new ConcurrentHashMap<>(); private final Map<String, PlaceholderExpansion> expansions = new ConcurrentHashMap<>();
private final ReentrantLock expansionsLock = new ReentrantLock(); private final ReentrantLock expansionsLock = new ReentrantLock();
public LocalExpansionManager(@NotNull final PlaceholderAPIBootstrap plugin) { public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
this.folder = new File(plugin., EXPANSIONS_FOLDER_NAME); this.folder = new File(plugin.getDataDirectory().toString(), EXPANSIONS_FOLDER_NAME);
this.logger = plugin.getLogger();
this.configManager = plugin.configManager();
if (!this.folder.exists() && !folder.mkdirs()) { if (!this.folder.exists() && !folder.mkdirs()) {
Msg.warn("Failed to create expansions folder!"); logger.atWarning().log("Failed to create expansions folder!");
} }
} }
@@ -183,8 +178,8 @@ public final class LocalExpansionManager /*implements Listener*/ {
Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!"); Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!");
if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) { if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) {
if (!Bukkit.getPluginManager().isPluginEnabled(expansion.getRequiredPlugin())) { if (HytaleServer.get().getPluginManager().getPlugin(PluginIdentifier.fromString(expansion.getRequiredPlugin())) == null) {
Msg.warn("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(), logger.atWarning().log("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(),
expansion.getRequiredPlugin()); expansion.getRequiredPlugin());
return Optional.empty(); return Optional.empty();
} }
@@ -193,7 +188,7 @@ public final class LocalExpansionManager /*implements Listener*/ {
expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL); expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL);
if (!expansion.register()) { if (!expansion.register()) {
Msg.warn("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier()); logger.atWarning().log("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier());
return Optional.empty(); return Optional.empty();
} }
@@ -207,7 +202,7 @@ public final class LocalExpansionManager /*implements Listener*/ {
reason = " - One of its properties is null which is not allowed!"; reason = " - One of its properties is null which is not allowed!";
} }
Msg.severe("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason); logger.atSevere().log("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason);
} }
return Optional.empty(); return Optional.empty();
@@ -229,50 +224,60 @@ public final class LocalExpansionManager /*implements Listener*/ {
// Avoid loading two external expansions with the same identifier // Avoid loading two external expansions with the same identifier
if (expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL && expansions.containsKey(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()); logger.atWarning().log("Failed to load external expansion %s. Identifier is already in use.", expansion.getIdentifier());
return false; return false;
} }
if (expansion instanceof Configurable) { if (expansion instanceof Configurable<?> configurable) {
Map<String, Object> defaults = ((Configurable) expansion).getDefaults(); final PlaceholderAPIConfig config = configManager.config();
String pre = "expansions." + identifier + ".";
FileConfiguration cfg = plugin.getConfig();
boolean save = false;
if (defaults != null) { if (!config.expansions().containsKey(expansion.getIdentifier())) {
for (Map.Entry<String, Object> entries : defaults.entrySet()) { config.expansions().put(expansion.getIdentifier(), configurable.provideDefault());
if (entries.getKey() == null || entries.getKey().isEmpty()) { configManager.save();
continue; } else {
} final Object expansionConfig = configManager.convertExpansion((Map<String, Object>) config.expansions().get(expansion.getIdentifier()), configurable.provideConfigType());
config.expansions().put(expansion.getIdentifier(), expansionConfig);
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();
} }
// Map<String, Object> defaults = ((Configurable<?>) expansion).getDefaults();
// String pre = "expansions." + identifier + ".";
// boolean save = false;
//
// final PlaceholderAPIConfig config = this.config.config();
//
// if (defaults != null) {
// for (Map.Entry<String, Object> 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) { // if (expansion instanceof VersionSpecific) {
VersionSpecific nms = (VersionSpecific) expansion; // VersionSpecific nms = (VersionSpecific) expansion;
if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { // if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) {
Msg.warn("Your server version is incompatible with expansion %s %s", // Msg.warn("Your server version is incompatible with expansion %s %s",
expansion.getIdentifier(), expansion.getVersion()); // expansion.getIdentifier(), expansion.getVersion());
return false; // return false;
} // }
} // }
final PlaceholderExpansion removed = getExpansion(identifier); final PlaceholderExpansion removed = getExpansion(identifier);
if (removed != null && !removed.unregister()) { if (removed != null && !removed.unregister()) {
@@ -280,7 +285,12 @@ public final class LocalExpansionManager /*implements Listener*/ {
} }
final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion);
Bukkit.getPluginManager().callEvent(event); final IEventDispatcher<ExpansionRegisterEvent, ExpansionRegisterEvent> eventDispatcher = HytaleServer.get().getEventBus().dispatchFor(ExpansionRegisterEvent.class);
if (eventDispatcher.hasListener()) {
eventDispatcher.dispatch(event);
}
// Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
return false; return false;
@@ -293,11 +303,11 @@ public final class LocalExpansionManager /*implements Listener*/ {
expansionsLock.unlock(); expansionsLock.unlock();
} }
if (expansion instanceof Listener) { // if (expansion instanceof Listener) {
Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); // Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin);
} // }
Msg.info( logger.at(Level.INFO).log(
"Successfully registered %s expansion: %s [%s]", "Successfully registered %s expansion: %s [%s]",
expansion.getExpansionType().name().toLowerCase(), expansion.getExpansionType().name().toLowerCase(),
expansion.getIdentifier(), expansion.getIdentifier(),
@@ -309,8 +319,8 @@ public final class LocalExpansionManager /*implements Listener*/ {
} }
// Check eCloud for updates only if the expansion is external // Check eCloud for updates only if the expansion is external
if (plugin.getPlaceholderAPIConfig().isCloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) { if (configManager.config().cloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) {
final Optional<CloudExpansion> cloudExpansionOptional = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); final Optional<CloudExpansion> cloudExpansionOptional = plugin.cloudExpansionManager().findCloudExpansionByName(identifier);
if (cloudExpansionOptional.isPresent()) { if (cloudExpansionOptional.isPresent()) {
CloudExpansion cloudExpansion = cloudExpansionOptional.get(); CloudExpansion cloudExpansion = cloudExpansionOptional.get();
cloudExpansion.setHasExpansion(true); cloudExpansion.setHasExpansion(true);
@@ -327,12 +337,15 @@ public final class LocalExpansionManager /*implements Listener*/ {
return false; return false;
} }
Bukkit.getPluginManager().callEvent(new ExpansionUnregisterEvent(expansion)); final IEventDispatcher<ExpansionUnregisterEvent, ExpansionUnregisterEvent> eventDispatcher = HytaleServer.get().getEventBus().dispatchFor(ExpansionUnregisterEvent.class);
if (eventDispatcher.hasListener()) {
if (expansion instanceof Listener) { eventDispatcher.dispatch(new ExpansionUnregisterEvent(expansion));
HandlerList.unregisterAll((Listener) expansion);
} }
// if (expansion instanceof Listener) {
// HandlerList.unregisterAll((Listener) expansion);
// }
if (expansion instanceof Taskable) { if (expansion instanceof Taskable) {
((Taskable) expansion).stop(); ((Taskable) expansion).stop();
} }
@@ -341,8 +354,8 @@ public final class LocalExpansionManager /*implements Listener*/ {
((Cacheable) expansion).clear(); ((Cacheable) expansion).clear();
} }
if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { if (configManager.config().cloudEnabled()) {
plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()) plugin.cloudExpansionManager().findCloudExpansionByName(expansion.getName())
.ifPresent(cloud -> { .ifPresent(cloud -> {
cloud.setHasExpansion(false); cloud.setHasExpansion(false);
cloud.setShouldUpdate(false); cloud.setShouldUpdate(false);
@@ -353,11 +366,11 @@ public final class LocalExpansionManager /*implements Listener*/ {
} }
private void registerAll(@NotNull final CommandSender sender) { private void registerAll(@NotNull final CommandSender sender) {
Msg.info("Placeholder expansion registration initializing..."); logger.at(Level.INFO).log("Placeholder expansion registration initializing...");
Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> {
if (exception != null) { if (exception != null) {
Msg.severe("Failed to load class files of expansion.", exception); logger.atSevere().log("Failed to load class files of expansion.", exception);
return; return;
} }
@@ -369,33 +382,31 @@ public final class LocalExpansionManager /*implements Listener*/ {
.collect(Collectors.toList()); .collect(Collectors.toList());
final long needsUpdate = registered.stream() final long needsUpdate = registered.stream()
.map(expansion -> plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null)) .map(expansion -> plugin.cloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null))
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(CloudExpansion::shouldUpdate) .filter(CloudExpansion::shouldUpdate)
.count(); .count();
StringBuilder message = new StringBuilder(registered.size() == 0 ? "&6" : "&a") Message message = Message.raw(registered.size() + "").color(registered.isEmpty() ? Color.YELLOW : Color.GREEN)
.append(registered.size()) .insert(" placeholder hook(s) registered!");
.append(' ')
.append("placeholder hook(s) registered!");
if (needsUpdate > 0) { if (needsUpdate > 0) {
message.append(' ') message = message.insert(" ")
.append("&6") .insert(Message.raw(needsUpdate + " placeholder hook(s) have an update available.").color(Color.YELLOW));
.append(needsUpdate)
.append(' ')
.append("placeholder hook(s) have an update available.");
} }
// logger.at(Level.INFO).log(message.toString());
sender.sendMessage(message);
Msg.msg(sender, message.toString()); final IEventDispatcher<ExpansionsLoadedEvent, ExpansionsLoadedEvent> eventDispatcher = HytaleServer.get().getEventBus().dispatchFor(ExpansionsLoadedEvent.class);
if (eventDispatcher.hasListener()) {
Bukkit.getPluginManager().callEvent(new ExpansionsLoadedEvent(registered)); eventDispatcher.dispatch(new ExpansionsLoadedEvent(registered));
}
}); });
} }
private void unregisterAll() { private void unregisterAll() {
for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { for (final PlaceholderExpansion expansion : new HashSet<>(expansions.values())) {
if (expansion.persist()) { if (expansion.persist()) {
continue; continue;
} }
@@ -424,7 +435,7 @@ public final class LocalExpansionManager /*implements Listener*/ {
final Class<? extends PlaceholderExpansion> expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class); final Class<? extends PlaceholderExpansion> expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class);
if (expansionClass == null) { if (expansionClass == null) {
Msg.severe("Failed to load expansion %s, as it does not have a class which" logger.atSevere().log("Failed to load expansion %s, as it does not have a class which"
+ " extends PlaceholderExpansion", file.getName()); + " extends PlaceholderExpansion", file.getName());
return null; return null;
} }
@@ -433,17 +444,17 @@ public final class LocalExpansionManager /*implements Listener*/ {
.map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) .map(method -> new MethodSignature(method.getName(), method.getParameterTypes()))
.collect(Collectors.toSet()); .collect(Collectors.toSet());
if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) { if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) {
Msg.severe("Failed to load expansion %s, as it does not have the required" logger.atSevere().log("Failed to load expansion %s, as it does not have the required"
+ " methods declared for a PlaceholderExpansion.", file.getName()); + " methods declared for a PlaceholderExpansion.", file.getName());
return null; return null;
} }
return expansionClass; return expansionClass;
} catch (VerifyError | NoClassDefFoundError e) { } catch (VerifyError | NoClassDefFoundError e) {
Msg.severe("Failed to load expansion %s (is a dependency missing?)", e, file.getName()); logger.atSevere().log("Failed to load expansion %s (is a dependency missing?)", e, file.getName());
return null; return null;
} catch (Exception e) { } catch (Exception e) {
plugin.getLogger().log(Level.SEVERE, "Failed to load expansion file: " + file.getAbsolutePath(), e); logger.atSevere().log("Failed to load expansion file: " + file.getAbsolutePath(), e);
return null; return null;
} }
}); });
@@ -460,39 +471,38 @@ public final class LocalExpansionManager /*implements Listener*/ {
throw ((LinkageError) ex.getCause()); throw ((LinkageError) ex.getCause());
} }
Msg.warn("There was an issue with loading an expansion."); logger.atWarning().log("There was an issue with loading an expansion.");
return null; return null;
} }
} }
public void onQuit(@NotNull final PlayerDisconnectEvent event) {
@EventHandler
public void onQuit(@NotNull final PlayerQuitEvent event) {
for (final PlaceholderExpansion expansion : getExpansions()) { for (final PlaceholderExpansion expansion : getExpansions()) {
if (!(expansion instanceof Cleanable)) { if (!(expansion instanceof Cleanable)) {
continue; continue;
} }
((Cleanable) expansion).cleanup(event.getPlayer()); ((Cleanable) expansion).cleanup(event.getPlayerRef());
} }
} }
@EventHandler(priority = EventPriority.HIGH) // @EventHandler(priority = EventPriority.HIGH)
public void onPluginDisable(@NotNull final PluginDisableEvent event) { //todo: hytale has no plugin disable event as of yet :(
final String name = event.getPlugin().getName(); // public void onPluginDisable() {
if (name.equals(plugin.getName())) { // final String name = event.getPlugin().getName();
return; // if (name.equals(plugin.getName())) {
} // return;
// }
for (final PlaceholderExpansion expansion : getExpansions()) { //
if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) { // for (final PlaceholderExpansion expansion : getExpansions()) {
continue; // if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) {
} // continue;
// }
expansion.unregister(); //
Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier()); // expansion.unregister();
Msg.info("Reason: required plugin %s was disabled.", name); // Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier());
} // Msg.info("Reason: required plugin %s was disabled.", name);
} // }
// }
} }

View File

@@ -21,14 +21,11 @@
package at.helpch.placeholderapi.listeners; package at.helpch.placeholderapi.listeners;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import org.bukkit.Bukkit; import com.hypixel.hytale.server.core.console.ConsoleSender;
import org.bukkit.event.EventHandler; import com.hypixel.hytale.server.core.event.events.PrepareUniverseEvent;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerLoadEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public final class ServerLoadEventListener implements Listener { public final class ServerLoadEventListener {
@NotNull @NotNull
private final PlaceholderAPIPlugin plugin; private final PlaceholderAPIPlugin plugin;
@@ -36,13 +33,12 @@ public final class ServerLoadEventListener implements Listener {
public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) { public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin); plugin.getEventRegistry().register(PrepareUniverseEvent.class, this::onServerLoad);
// Bukkit.getPluginManager().registerEvents(this, plugin);
} }
@EventHandler public void onServerLoad(@NotNull final PrepareUniverseEvent event) {
public void onServerLoad(@NotNull final ServerLoadEvent event) { plugin.localExpansionManager().load(ConsoleSender.INSTANCE);
HandlerList.unregisterAll(this);
plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender());
} }
} }

View File

@@ -24,8 +24,7 @@ import java.util.Locale;
import java.util.function.Function; import java.util.function.Function;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.ChatColor; import com.hypixel.hytale.server.core.entity.entities.Player;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -41,7 +40,7 @@ public final class CharsReplacer implements Replacer {
@NotNull @NotNull
@Override @Override
public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, public String apply(@NotNull final String text, @Nullable final Player player,
@NotNull final Function<String, @Nullable PlaceholderExpansion> lookup) { @NotNull final Function<String, @Nullable PlaceholderExpansion> lookup) {
final char[] chars = text.toCharArray(); final char[] chars = text.toCharArray();
final StringBuilder builder = new StringBuilder(text.length()); final StringBuilder builder = new StringBuilder(text.length());

View File

@@ -23,14 +23,15 @@ package at.helpch.placeholderapi.replacer;
import java.util.function.Function; import java.util.function.Function;
import at.helpch.placeholderapi.expansion.PlaceholderExpansion; import at.helpch.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.OfflinePlayer; import com.hypixel.hytale.server.core.entity.entities.Player;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public interface Replacer { public interface Replacer {
@NotNull @NotNull
String apply(@NotNull final String text, @Nullable final OfflinePlayer player, String apply(@NotNull final String text, @Nullable final Player player,
@NotNull final Function<String, @Nullable PlaceholderExpansion> lookup); @NotNull final Function<String, @Nullable PlaceholderExpansion> lookup);

View File

@@ -1,80 +0,0 @@
package at.helpch.placeholderapi.util;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
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" +
"###############################################";
private final PlaceholderAPIPlugin main;
public ExpansionSafetyCheck(@NotNull final PlaceholderAPIPlugin main) {
this.main = main;
}
public boolean runChecks() {
if (!main.getPlaceholderAPIConfig().detectMaliciousExpansions()) {
return false;
}
final File expansionsFolder = new File(main.getDataFolder(), "expansions");
if (!expansionsFolder.exists()) {
return false;
}
final Set<String> knownMaliciousExpansions;
try {
final String hashes = Resources.toString(new URL("https://check.placeholderapi.com"), StandardCharsets.UTF_8);
knownMaliciousExpansions = Arrays.stream(hashes.split("\n")).collect(Collectors.toSet());
} catch (Exception e) {
main.getLogger().log(Level.SEVERE, "Failed to download anti malware hash check list from https://check.placeholderapi.com", e);
return false;
}
final Set<String> maliciousPaths = new HashSet<>();
for (File file : expansionsFolder.listFiles()) {
try {
final String hash = Hashing.sha256().hashBytes(Files.asByteSource(file).read()).toString();
if (knownMaliciousExpansions.contains(hash)) {
maliciousPaths.add(file.getAbsolutePath());
}
} catch (Exception e) {
main.getLogger().log(Level.SEVERE, "Error occurred while trying to read " + file.getAbsolutePath(), e);
}
}
if (maliciousPaths.isEmpty()) {
return false;
}
main.getLogger().severe(String.format(MESSAGE, maliciousPaths.stream().map(p -> "HASH OF " + p + " MATCHES KNOWN MALICIOUS EXPANSION DELETE IMMEDIATELY\n").collect(Collectors.joining())));
main.getServer().shutdown();
return true;
}
}

View File

@@ -29,8 +29,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import at.helpch.placeholderapi.PlaceholderAPIPlugin; import at.helpch.placeholderapi.PlaceholderAPIPlugin;
import org.bukkit.Bukkit; import com.hypixel.hytale.server.core.universe.Universe;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public final class Futures { public final class Futures {
@@ -42,11 +41,9 @@ public final class Futures {
@NotNull final CompletableFuture<T> future, @NotNull final CompletableFuture<T> future,
@NotNull final BiConsumer<T, Throwable> consumer) { @NotNull final BiConsumer<T, Throwable> consumer) {
future.whenComplete((value, exception) -> { future.whenComplete((value, exception) -> {
if (Bukkit.isPrimaryThread()) { Universe.get().getDefaultWorld().execute(() -> consumer.accept(value, exception));
consumer.accept(value, exception); // plugin.getTaskRegistry().registerTask(() -> consumer.accept(value, exception));
} else { // plugin.getScheduler().runTask(() -> consumer.accept(value, exception));
plugin.getScheduler().runTask(() -> consumer.accept(value, exception));
}
}); });
} }

View File

@@ -1,80 +0,0 @@
/*
* This file is part of PlaceholderAPI
*
* PlaceholderAPI
* Copyright (c) 2015 - 2026 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 <http://www.gnu.org/licenses/>.
*/
package at.helpch.placeholderapi.util;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.stream.Collectors;
import at.helpch.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);
}
}

View File

@@ -10,7 +10,7 @@
# Download placeholders: /papi ecloud # Download placeholders: /papi ecloud
check_updates: true check_updates: true
cloud_enabled: true cloud_enabled: true
cloud_sorting: "name" cloud_sorting: "NAME"
boolean_value: boolean_value:
true_value: 'yes' true_value: 'yes'
false_value: 'no' false_value: 'no'

View File

@@ -0,0 +1,14 @@
{
"Group": "HelpChat",
"Name": "PlaceholderAPI",
"Version": "1.0.0",
"Description": "An awesome placeholder provider",
"Authors": [{"Name": "Your Mama"}],
"Website": "https://placeholderapi.com",
"ServerVersion": "*",
"Dependencies": {},
"OptionalDependencies": {},
"DisabledByDefault": false,
"Main": "at.helpch.placeholderapi.PlaceholderAPIPlugin",
"IncludesAssetPack": false
}