Compare commits

...
7 Commits
Author SHA1 Message Date
Andre_601 6aaa169a86 Merge pull request #2 from Andre601/feature/improved-condition-parsing
Better condition parsing
2022-08-02 01:44:00 +02:00
Andre601 091a97076e Fix inverted check and add hidePlayers option 2022-08-02 01:43:37 +02:00
Andre601 d79733cafc Pushing changes recommended by @bergerkiller and @bbayu123 2022-08-02 00:56:54 +02:00
Andre601 99793f5c8a Get rid of ConditionsHolder in favour of Expression 2022-08-01 23:41:07 +02:00
Andre601 8d3cd980cf Move ConditionsHolder and Expression to own folder 2022-08-01 23:25:17 +02:00
Andre601 3e40ad34ab Better condition parsing 2022-08-01 23:18:33 +02:00
Andre601 356bc09c09 Version 1.1.0
- Add ${server host} placeholder to show the pinged server address
- Improved Placeholders class
- Improved StringReplacer to have a static method instead of constantly making new instances.
- Update default.yml with better examples and descriptions.
2022-07-27 16:28:00 +02:00
20 changed files with 451 additions and 243 deletions

No files matched your search

@@ -30,6 +30,7 @@ import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.ProfileManager;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.core.profiles.replacer.Placeholders;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.chat.TextComponent;
@@ -58,8 +59,14 @@ public class PingEvent implements Listener{
return;
InetSocketAddress address = (InetSocketAddress)event.getConnection().getSocketAddress();
Map<String, Object> replacements = plugin.getCore()
.loadPlaceholders(protocol.getProtocol(), ping.getPlayers().getOnline(), ping.getPlayers().getMax(), address);
InetSocketAddress host = event.getConnection().getVirtualHost();
Map<String, Object> replacements = Placeholders.get(plugin.getCore())
.withProtocol(protocol.getProtocol())
.withPlayersOnline(ping.getPlayers().getOnline())
.withPlayersMax(ping.getPlayers().getMax())
.withPlayerName(address)
.withHostAddress(host)
.getReplacements();
ServerListProfile profile = ProfileManager.get(plugin.getCore())
.replacements(replacements)
@@ -78,6 +85,16 @@ public class PingEvent implements Listener{
ping.setDescriptionComponent(component);
}
if(profile.shouldHidePlayers()){
ping.setPlayers(null);
ping.setFavicon(ping.getFaviconObject());
ping.setVersion(protocol);
event.setResponse(ping);
return;
}
if(!profile.getPlayerCount().isEmpty()){
protocol.setName(ComponentParser.text(profile.getPlayerCount())
.replacements(replacements)
@@ -93,6 +110,7 @@ public class PingEvent implements Listener{
ServerPing.PlayerInfo[] playerInfos = AdvancedServerList.getPlayers(ServerPing.PlayerInfo.class, players)
.toArray(new ServerPing.PlayerInfo[0]);
if(playerInfos.length > 0)
ping.getPlayers().setSample(playerInfos);
@@ -44,8 +44,8 @@ public class BungeeLogger implements PluginLogger{
}
@Override
public void warn(String msg){
logger.warning(msg);
public void warn(String msg, Object... args){
logger.warning(String.format(msg, args));
}
@Override
@@ -29,15 +29,12 @@ import ch.andre601.advancedserverlist.core.commands.CommandHandler;
import ch.andre601.advancedserverlist.core.file.FileHandler;
import ch.andre601.advancedserverlist.core.interfaces.PluginCore;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.players.PlayerHandler;
import ch.andre601.advancedserverlist.core.profiles.replacer.Placeholders;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.*;
@@ -69,9 +66,7 @@ public class AdvancedServerList{
constructor.setAccessible(true);
for(String line : lines){
players.add(constructor.newInstance(
ComponentParser.text(line).toString(), UUID.randomUUID()
));
players.add(constructor.newInstance(line, UUID.randomUUID()));
}
return players;
@@ -80,17 +75,6 @@ public class AdvancedServerList{
}
}
public Map<String, Object> loadPlaceholders(int protocol, int online, int max, InetSocketAddress ip){
Map<String, Object> replacements = new HashMap<>();
replacements.put(Placeholders.PLAYER_PROTOCOL, protocol);
replacements.put(Placeholders.PLAYERS_ONLINE, online);
replacements.put(Placeholders.PLAYERS_MAX, max);
replacements.put(Placeholders.PLAYER_NAME, getPlayerHandler().getPlayerByIp(ip.getHostString()));
return replacements;
}
public void disable(){
getPluginLogger().info("Saving cache.data file...");
getPlayerHandler().save();
@@ -130,7 +130,7 @@ public class FileHandler{
if(tmp == null)
continue;
profiles.add(new ServerListProfile(tmp));
profiles.add(new ServerListProfile(tmp, logger));
logger.info("Loaded " + file.getName());
}
@@ -29,7 +29,7 @@ public interface PluginLogger{
void info(String msg, Object... args);
void warn(String msg);
void warn(String msg, Object... args);
void warn(String msg, Throwable throwable);
}
@@ -38,12 +38,10 @@ public class ComponentParser{
private static final MiniMessage mm;
private static final LegacyComponentSerializer legacy;
private static final StringReplacer replacer;
static {
mm = MiniMessage.miniMessage();
legacy = LegacyComponentSerializer.legacySection();
replacer = new StringReplacer();
}
private String text;
@@ -61,17 +59,17 @@ public class ComponentParser{
}
public ComponentParser replacements(Map<String, Object> replacements){
replacements.forEach(replacer::add);
text = StringReplacer.replace(text, replacements);
return this;
}
public ComponentParser function(Function<String, String> function){
public ComponentParser modifyText(Function<String, String> function){
this.text = function.apply(text);
return this;
}
public Component toComponent(){
return mm.deserialize(replacer.replace(text));
return mm.deserialize(text);
}
@Override
@@ -1,139 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022 Andre_601
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package ch.andre601.advancedserverlist.core.profiles;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ConditionsHolder{
private final List<String> expressions = new ArrayList<>();
private final StringReplacer replacer = new StringReplacer();
public ConditionsHolder(List<String> expressions){
if(expressions != null && !expressions.isEmpty())
this.expressions.addAll(expressions);
}
public void replace(String from, Object to){
replacer.add(from, to);
}
public boolean eval(PluginLogger logger){
if(expressions.isEmpty())
return true;
for(String expression : expressions){
if(!parseExpression(expression, logger))
return false;
}
return true;
}
private boolean parseExpression(String expression, PluginLogger logger){
if(expression == null || expression.isEmpty())
return true;
String newExpression = replacer.replace(expression);
char[] chars = newExpression.toCharArray();
StringBuilder left = new StringBuilder();
StringBuilder operator = new StringBuilder();
StringBuilder right = new StringBuilder();
boolean operatorFound = false;
for(int i = 0; i < chars.length; i++){
char c = chars[i];
if(c == ' ')
continue;
if((c != '<' && c != '>' && c != '=' && c != '!') || i + 1 >= chars.length){
if(operatorFound){
right.append(c);
continue;
}
left.append(c);
continue;
}
if(operatorFound){
logger.warn("Encountered second operator in condition! AdvancedServerList currently only supports one operator!");
return false;
}
operatorFound = true;
char next = chars[i + 1];
if(c == '!' && next != '='){
logger.warn("Invalid condition found. Expected '!=' but found '!" + next + "' in condition " + newExpression);
return false;
}
operator.append(c);
i++;
if(c == '!' || ((c == '<' || c == '>') && next == '=')){
operator.append(next);
}
}
if(left.isEmpty() || operator.isEmpty() || right.isEmpty()){
logger.warn("Failed to evaluate condition. One part of the expression was empty!");
return false;
}
int leftInt = tryParse(left.toString());
int rightInt = tryParse(right.toString());
return switch(operator.toString().toLowerCase(Locale.ROOT)){
case ">" -> leftInt > rightInt;
case ">=" -> leftInt >= rightInt;
case "=" -> left.toString().equals(right.toString());
case "!=" -> !left.toString().equals(right.toString());
case "<" -> leftInt < rightInt;
case "<=" -> leftInt <= rightInt;
default -> false;
};
}
private int tryParse(String value){
try{
return Integer.parseInt(value);
}catch(NumberFormatException ex){
return value.length();
}
}
}
@@ -26,7 +26,6 @@
package ch.andre601.advancedserverlist.core.profiles;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import java.util.HashMap;
import java.util.Map;
@@ -54,10 +53,8 @@ public class ProfileManager{
for(ServerListProfile profile : core.getFileHandler().getProfiles()){
if(profile.getMotd().isEmpty() && profile.getPlayers().isEmpty() && profile.getPlayerCount().isEmpty())
continue;
ConditionsHolder conditions = profile.getConditions();
replacements.forEach(conditions::replace);
if(conditions.eval(core.getPluginLogger()))
if(profile.evalConditions(replacements))
return profile;
}
@@ -25,32 +25,34 @@
package ch.andre601.advancedserverlist.core.profiles;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.conditions.Expression;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ServerListProfile{
private final ConditionsHolder conditions;
private final int priority;
private final List<Expression> expressions;
private final List<String> motd;
private final List<String> players;
private final String playerCount;
private final boolean hidePlayers;
public ServerListProfile(ConfigurationNode node){
this.conditions = new ConditionsHolder(getList(node, "conditions", false));
public ServerListProfile(ConfigurationNode node, PluginLogger logger){
this.priority = node.node("priority").getInt();
this.expressions = createExpressions(getList(node, "conditions", false), logger);
this.motd = getList(node, "motd", true);
this.players = getList(node, "players", false);
this.playerCount = node.node("playerCount").getString("");
}
public ConditionsHolder getConditions(){
return conditions;
this.hidePlayers = node.node("hidePlayers").getBoolean();
}
public int getPriority(){
@@ -69,6 +71,44 @@ public class ServerListProfile{
return playerCount;
}
public boolean shouldHidePlayers(){
return hidePlayers;
}
public boolean evalConditions(Map<String, Object> replacements){
if(expressions.isEmpty())
return true;
for(Expression expression : expressions){
if(!expression.evaluate(replacements)){
return false;
}
}
return true;
}
private List<Expression> createExpressions(List<String> list, PluginLogger logger) {
if(list.isEmpty())
return Collections.emptyList();
List<Expression> expressions = new ArrayList<>();
for(String str : list){
Expression expression = new Expression(str);
switch(expression.getResult()){
case VALID -> expressions.add(expression);
case INVALID_EMPTY_PARTS -> logInvalid(logger, str, "Either left or right part of condition was empty.");
case INVALID_NO_EXPRESSION -> logInvalid(logger, str, "Empty conditions are not allowed.");
case INVALID_DOUBLE_OPERATOR -> logInvalid(logger, str, "Condition had two operands!");
case INVALID_BROKEN_NOT_EQUAL -> logInvalid(logger, str, "Found '!' without '=' following it.");
default -> logInvalid(logger, str, "Encountered unknown issue.");
}
}
return expressions;
}
private List<String> getList(ConfigurationNode node, String key, boolean trim){
List<String> list;
try{
@@ -85,4 +125,8 @@ public class ServerListProfile{
return list;
}
private void logInvalid(PluginLogger logger, String expression, String reason){
logger.warn("Invalid Condition '%s'! %s", expression, reason);
}
}
@@ -0,0 +1,208 @@
/*
* MIT License
*
* Copyright (c) 2022 Andre_601
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import java.util.Map;
public class Expression{
private ExpressionResult result = ExpressionResult.VALID;
private String left;
private Operator operator = Operator.UNKNOWN;
private String right;
public Expression(String expression){
resolveExpression(expression);
}
public boolean evaluate(Map<String, Object> replacements){
String newLeft = StringReplacer.replace(left, replacements);
String newRight = StringReplacer.replace(right, replacements);
return operator.evaluate(newLeft, newRight);
}
public ExpressionResult getResult(){
return result;
}
private void resolveExpression(String expression){
if(expression == null || expression.isEmpty()){
result = ExpressionResult.INVALID_NO_EXPRESSION;
return;
}
char[] chars = expression.toCharArray();
StringBuilder left = new StringBuilder();
StringBuilder right = new StringBuilder();
boolean foundOperator = false;
for(int i = 0; i < chars.length; i++){
char c = chars[i];
if((c != '<' && c != '>' && c != '=' && c != '!') || i + 1 >= chars.length){
if(foundOperator){
right.append(c);
}else{
left.append(c);
}
continue;
}
if(foundOperator){
result = ExpressionResult.INVALID_DOUBLE_OPERATOR;
return;
}
foundOperator = true;
char next = chars[i + 1];
if(c == '!' && next != '='){
result = ExpressionResult.INVALID_BROKEN_NOT_EQUAL;
return;
}
operator = Operator.getOperand(c, next);
if(operator.hasSecond() && operator != Operator.UNKNOWN)
i++;
}
if(left.isEmpty() || right.isEmpty()){
result = ExpressionResult.INVALID_EMPTY_PARTS;
return;
}
this.left = left.toString();
this.right = right.toString();
}
public enum Operator{
LESS_THAN('<', '\0'){
@Override
public boolean evaluate(String left, String right){
int leftInt = Operator.getInt(left);
int rightInt = Operator.getInt(right);
return leftInt < rightInt;
}
},
LESS_OR_EQUAL('<', '='){
@Override
public boolean evaluate(String left, String right){
int leftInt = Operator.getInt(left);
int rightInt = Operator.getInt(right);
return leftInt <= rightInt;
}
},
EQUAL('=', '\0'){
@Override
public boolean evaluate(String left, String right){
return left.equals(right);
}
},
NOT_EQUAL('!', '='){
@Override
public boolean evaluate(String left, String right){
return !left.equals(right);
}
},
GREATER_THAN('>', '\0'){
@Override
public boolean evaluate(String left, String right){
int leftInt = Operator.getInt(left);
int rightInt = Operator.getInt(right);
return leftInt > rightInt;
}
},
GREATER_OR_EQUAL('>', '='){
@Override
public boolean evaluate(String left, String right){
int leftInt = Operator.getInt(left);
int rightInt = Operator.getInt(right);
return leftInt >= rightInt;
}
},
UNKNOWN('\0', '\0'){
@Override
public boolean evaluate(String left, String right){
return false;
}
};
private static final Operator[] VALUES = values();
private final char first;
private final char second;
Operator(char first, char second){
this.first = first;
this.second = second;
}
public static Operator getOperand(char first, char second){
for(Operator operator : VALUES){
if(operator.first == first){
if((!operator.hasSecond() && second != '=') || operator.second == second)
return operator;
}
}
return Operator.UNKNOWN;
}
public boolean hasSecond(){
return second != '\0';
}
public abstract boolean evaluate(String left, String right);
private static int getInt(String text){
try{
return Integer.parseInt(text);
}catch(NumberFormatException ex){
return text.length();
}
}
}
public enum ExpressionResult{
VALID,
INVALID_NO_EXPRESSION,
INVALID_DOUBLE_OPERATOR,
INVALID_BROKEN_NOT_EQUAL,
INVALID_EMPTY_PARTS
}
}
@@ -25,12 +25,69 @@
package ch.andre601.advancedserverlist.core.profiles.replacer;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
public class Placeholders{
public static final String PLAYERS_ONLINE = "${players online}";
public static final String PLAYERS_MAX = "${players max}";
private final AdvancedServerList core;
private final Map<String, Object> replacements;
public static final String PLAYER_NAME = "${player name}";
public static final String PLAYER_PROTOCOL = "${player protocol}";
public static final String PLAYER_VERSION = "${player version}";
public Placeholders(AdvancedServerList core){
this.core = core;
this.replacements = new HashMap<>();
}
public static Placeholders get(AdvancedServerList core){
return new Placeholders(core);
}
public Placeholders withProtocol(int protocol){
this.replacements.put("${player protocol}", protocol);
return this;
}
public Placeholders withPlayersOnline(int online){
this.replacements.put("${players online}", online);
return this;
}
public Placeholders withPlayersMax(int max){
this.replacements.put("${players max}", max);
return this;
}
public Placeholders withPlayerName(InetSocketAddress playerAddress){
if(playerAddress != null)
this.replacements.put("${player name}", core.getPlayerHandler().getPlayerByIp(playerAddress.getHostString()));
return this;
}
public Placeholders withHostAddress(InetSocketAddress hostAddress){
if(hostAddress != null)
this.replacements.put("${server host}", hostAddress.getHostString());
return this;
}
public Placeholders withHostAddress(String hostAddress){
if(hostAddress != null)
this.replacements.put("${server host}", hostAddress);
return this;
}
public Placeholders withPlayerVersion(String version){
this.replacements.put("${player version}", version);
return this;
}
public Map<String, Object> getReplacements(){
return replacements;
}
}
@@ -25,42 +25,14 @@
package ch.andre601.advancedserverlist.core.profiles.replacer;
import java.util.Iterator;
import java.util.Map;
/*
* Original by Imo van den Berge (aka Bergerkiller: https://github.com/Bergerkiller)
*
* Original Source: https://github.com/bergerhealer/BKCommonLib/blob/master/src/main/java/com/bergerkiller/bukkit/common/StringReplaceBundle.java
*/
public class StringReplacer{
private final EntryList<String, Object> entries = new EntryList<>();
public void add(String from, Object to){
if(from == null || to == null)
return;
entries.add(from, to);
}
public Object get(String from){
Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
Map.Entry<String, Object> entry;
while(iterator.hasNext()){
entry = iterator.next();
if(entry.getKey().equals(from)){
iterator.remove();
return entry.getValue();
}
}
return null;
}
public String replace(String input){
public static String replace(String input, Map<String, Object> replacements){
StringBuilder output = new StringBuilder(input);
int index;
for(Map.Entry<String, Object> entry : entries){
for(Map.Entry<String, Object> entry : replacements.entrySet()){
index = 0;
while((index = output.indexOf(entry.getKey(), index)) != -1){
output.replace(index, index + entry.getKey().length(), String.valueOf(entry.getValue()));
+24 -9
View File
@@ -17,29 +17,44 @@ priority: 0
#
# Set the MOTD that should be displayed.
# Can be removed or set to "motd: []" to not alter the MOTD.
# Supports HEX colors for 1.16+ servers including gradients using MiniMessage's <gradient:color:color> format.
#
# Remove this option or set it to motd: [] to not alter the MOTD.
#
# Read more: https://github.com/Andre601/AdvancedServerList/wiki/Profiles#motd
#
motd:
- 'Line 1'
- 'Line 2'
- '<grey>Line 1'
- '<grey>Line 2'
#
# Sets if players should be hidden.
# When set to true will the player count be replaced with ???
# Additionally will the options 'players' and 'playerCount' be ignored by the plugin.
#
# Read more: https://github.com/Andre601/AdvancedServerList/wiki/Profiles#hideplayers
#
hidePlayers: false
#
# Set the hover text that usually displays online players.
# Can be removed or set to "players: []" to not alter the player list.
# Only normal colours such as <grey> or <aqua> are supported.
#
# Remove this option or set it to players: [] to not alter the hover text.
#
# Read more: https://github.com/Andre601/AdvancedServerList/wiki/Profiles#players
#
players:
- 'Line 1'
- 'Line 2'
- 'Line 3'
- '<grey>Line 1'
- '<grey>Line 2'
- '<grey>Line 3'
#
# Set the text that usually shows online players and max that can join.
# Can be removed or set to "playerCount: ''" to not alter the player count text.
# Only normal colours such as <grey> or <aqua> are supported.
#
# Remove this option or set it to playerCount: '' to not alter the player count text.
#
# Read more: https://github.com/Andre601/AdvancedServerList/wiki/Profiles#playercount
#
playerCount: 'Text'
playerCount: '<grey>Text'
@@ -28,6 +28,7 @@ package ch.andre601.advancedserverlist.paper.events;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.ProfileManager;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.core.profiles.replacer.Placeholders;
import ch.andre601.advancedserverlist.paper.PaperCore;
import com.destroystokyo.paper.event.server.PaperServerListPingEvent;
import com.destroystokyo.paper.profile.PlayerProfile;
@@ -55,8 +56,14 @@ public class PingEvent implements Listener{
@EventHandler
public void onServerPing(PaperServerListPingEvent event){
InetSocketAddress address = event.getClient().getAddress();
Map<String, Object> replacements = plugin.getCore()
.loadPlaceholders(event.getClient().getProtocolVersion(), event.getNumPlayers(), event.getMaxPlayers(), address);
InetSocketAddress host = event.getClient().getVirtualHost();
Map<String, Object> replacements = Placeholders.get(plugin.getCore())
.withProtocol(event.getClient().getProtocolVersion())
.withPlayersOnline(event.getNumPlayers())
.withPlayersMax(event.getMaxPlayers())
.withPlayerName(address)
.withHostAddress(host)
.getReplacements();
ServerListProfile profile = ProfileManager.get(plugin.getCore())
.replacements(replacements)
@@ -70,7 +77,7 @@ public class PingEvent implements Listener{
if(!profile.getMotd().isEmpty()){
event.motd(ComponentParser.list(profile.getMotd())
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -79,10 +86,15 @@ public class PingEvent implements Listener{
.toComponent());
}
if(profile.shouldHidePlayers()){
event.setHidePlayers(true);
return;
}
if(!profile.getPlayerCount().isEmpty()){
event.setVersion(ComponentParser.text(profile.getPlayerCount())
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -104,7 +116,7 @@ public class PingEvent implements Listener{
List<PlayerProfile> players = new ArrayList<>();
lines.forEach(line -> players.add(Bukkit.createProfile(UUID.randomUUID(), ComponentParser.text(line)
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -44,8 +44,8 @@ public class PaperLogger implements PluginLogger{
}
@Override
public void warn(String msg){
logger.warning(msg);
public void warn(String msg, Object... args){
logger.warning(String.format(msg, args));
}
@Override
+1 -1
View File
@@ -12,7 +12,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<plugin.version>1.0.3</plugin.version>
<plugin.version>1.2.0</plugin.version>
<plugin.description>Create multiple Server lists based on conditions.</plugin.description>
<plugin.depend.mc>1.19-R0.1-SNAPSHOT</plugin.depend.mc>
@@ -28,6 +28,7 @@ package ch.andre601.advancedserverlist.spigot.events;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.ProfileManager;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.core.profiles.replacer.Placeholders;
import ch.andre601.advancedserverlist.spigot.SpigotCore;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolManager;
@@ -51,6 +52,8 @@ public class PingEvent implements Listener{
private final SpigotCore plugin;
private final ProtocolManager protocolManager;
private final Map<String, String> hostAddresses = new HashMap<>();
public PingEvent(SpigotCore plugin, ProtocolManager protocolManager){
this.plugin = plugin;
this.protocolManager = protocolManager;
@@ -59,6 +62,19 @@ public class PingEvent implements Listener{
}
private void loadPacketListener(SpigotCore spigotPlugin){
protocolManager.addPacketListener(new PacketAdapter(spigotPlugin, ListenerPriority.LOW, PacketType.Handshake.Client.SET_PROTOCOL){
@Override
public void onPacketReceiving(PacketEvent event){
InetSocketAddress address = event.getPlayer().getAddress();
if(address == null)
return;
String host = event.getPacket().getStrings().read(0);
hostAddresses.put(address.getHostString(), host);
}
});
protocolManager.addPacketListener(new PacketAdapter(spigotPlugin, ListenerPriority.LOW, PacketType.Status.Server.SERVER_INFO){
@Override
public void onPacketSending(PacketEvent event){
@@ -67,8 +83,15 @@ public class PingEvent implements Listener{
if(address == null)
return;
Map<String, Object> replacements = spigotPlugin.getCore()
.loadPlaceholders(ping.getVersionProtocol(), ping.getPlayersOnline(), ping.getPlayersMaximum(), address);
Map<String, Object> replacements = Placeholders.get(spigotPlugin.getCore())
.withProtocol(ping.getVersionProtocol())
.withPlayersOnline(ping.getPlayersOnline())
.withPlayersMax(ping.getPlayersMaximum())
.withPlayerName(address)
.withHostAddress(hostAddresses.get(address.getHostString()))
.getReplacements();
spigotPlugin.getPluginLogger().info(hostAddresses.get(address.getHostString()));
ServerListProfile profile = ProfileManager.get(spigotPlugin.getCore())
.replacements(replacements)
@@ -82,7 +105,7 @@ public class PingEvent implements Listener{
if(!profile.getMotd().isEmpty()){
Component component = ComponentParser.list(profile.getMotd())
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -92,10 +115,15 @@ public class PingEvent implements Listener{
ping.setMotD(AdventureComponentConverter.fromComponent(component));
}
if(profile.shouldHidePlayers()){
ping.setPlayersVisible(false);
return;
}
if(!profile.getPlayerCount().isEmpty()){
ping.setVersionName(ComponentParser.text(profile.getPlayerCount())
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -110,7 +138,7 @@ public class PingEvent implements Listener{
ping.setPlayers(getFakePlayers(
ComponentParser.list(profile.getPlayers())
.replacements(replacements)
.function(text -> {
.modifyText(text -> {
if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI"))
return PlaceholderAPI.setPlaceholders(player, text);
@@ -44,8 +44,8 @@ public class SpigotLogger implements PluginLogger{
}
@Override
public void warn(String msg){
logger.warning(msg);
public void warn(String msg, Object... args){
logger.warning(String.format(msg, args));
}
@Override
@@ -59,10 +59,16 @@ public class PingEvent{
ServerPing.Builder builder = ping.asBuilder();
InetSocketAddress address = event.getConnection().getRemoteAddress();
InetSocketAddress host = event.getConnection().getVirtualHost().orElse(null);
Map<String, Object> replacements = plugin.getCore()
.loadPlaceholders(protocol.getProtocol(), builder.getOnlinePlayers(), builder.getMaximumPlayers(), address);
replacements.put(Placeholders.PLAYER_VERSION, ProtocolVersion.getProtocolVersion(protocol.getProtocol()));
Map<String, Object> replacements = Placeholders.get(plugin.getCore())
.withProtocol(protocol.getProtocol())
.withPlayersOnline(builder.getOnlinePlayers())
.withPlayersMax(builder.getMaximumPlayers())
.withPlayerName(address)
.withHostAddress(host)
.withPlayerVersion(ProtocolVersion.getProtocolVersion(protocol.getProtocol()).toString())
.getReplacements();
ServerListProfile profile = ProfileManager.get(plugin.getCore())
.replacements(replacements)
@@ -79,6 +85,13 @@ public class PingEvent{
);
}
if(profile.shouldHidePlayers()){
builder.nullPlayers();
event.setPing(builder.build());
return;
}
if(!profile.getPlayerCount().isEmpty()){
builder.version(new ServerPing.Version(
-1,
@@ -92,6 +105,7 @@ public class PingEvent{
String players = ComponentParser.list(profile.getPlayers())
.replacements(replacements)
.toString();
ServerPing.SamplePlayer[] playerSamples = AdvancedServerList.getPlayers(ServerPing.SamplePlayer.class, players)
.toArray(new ServerPing.SamplePlayer[0]);
@@ -42,8 +42,8 @@ public class VelocityLogger implements PluginLogger{
}
@Override
public void warn(String msg){
logger.warn(msg);
public void warn(String msg, Object... args){
logger.warn(msg, args);
}
@Override