Compare commits

...
32 changed files with 969 additions and 399 deletions

No files matched your search

+2 -2
View File
@@ -8,12 +8,12 @@ To ensure proper safety and support are only certain versions and Platforms of A
|---------------|-----------|
| v5 | Yes |
| v4 | Yes* |
| v3 | Yes** |
| v3 | No** |
| v2 | No |
| v1 | No |
\*Only receives support but no updates or bug fixes.
\*\*Support ends at the end of 2024.
\*\*Support ended on December 31st, 2024.
## Supported Server/Proxy Versions
+65
View File
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent</artifactId>
<groupId>ch.andre601.advancedserverlist</groupId>
<version>parent</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>asl-placeholderapi</artifactId>
<packaging>jar</packaging>
<version>${plugin.version}</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compuler.target>16</maven.compuler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>papermc-repo</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>placeholderapi-repo</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.21-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>AdvancedServerList-PlaceholderAPI-Addon-${plugin.version}</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,70 @@
package ch.andre601.placeholderapi;
import ch.andre601.placeholderapi.messenger.ASLPluginMessageListener;
import ch.andre601.placeholderapi.messenger.BungeeCordMessageListener;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.concurrent.Callable;
import java.util.logging.Level;
public final class ASLPlaceholderAPI extends JavaPlugin{
private String serverName = null;
@Override
public void onEnable(){
// Own Plugin Channel
getServer().getMessenger().registerOutgoingPluginChannel(this, pluginChannel());
getServer().getMessenger().registerIncomingPluginChannel(this, pluginChannel(), new ASLPluginMessageListener(this));
// BungeeCord Plugin Channel
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessageListener(this));
requestServerName();
}
@Override
public void onDisable(){
getServer().getMessenger().unregisterOutgoingPluginChannel(this);
getServer().getMessenger().unregisterIncomingPluginChannel(this);
}
public void serverName(String serverName){
this.serverName = serverName;
}
public String pluginChannel(){
return "advancedserverlist:action";
}
public String serverName(){
return serverName;
}
public void waitUntil(Callable<Boolean> condition, Runnable action){
Bukkit.getScheduler().runTaskTimer(this, (task) -> {
try{
if(condition.call()){
action.run();
task.cancel();
}
}catch(Exception ex){
getLogger().log(Level.WARNING, "Encountered Exception while waiting for a task to finish.", ex);
}
}, 0L, 1L);
}
private void requestServerName(){
waitUntil(() -> !getServer().getOnlinePlayers().isEmpty(), () -> {
Player plmSender = Bukkit.getOnlinePlayers().iterator().next();
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("GetServer");
plmSender.sendPluginMessage(this, "BungeeCord", out.toByteArray());
});
}
}
@@ -0,0 +1,78 @@
package ch.andre601.placeholderapi.messenger;
import ch.andre601.placeholderapi.ASLPlaceholderAPI;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.UUID;
import java.util.logging.Level;
public class ASLPluginMessageListener implements PluginMessageListener{
private final ASLPlaceholderAPI plugin;
public ASLPluginMessageListener(ASLPlaceholderAPI plugin){
this.plugin = plugin;
}
@Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message){
if(!channel.equals(plugin.pluginChannel()))
return;
if(plugin.serverName() == null)
return;
ByteArrayInputStream stream = new ByteArrayInputStream(message);
DataInputStream in = new DataInputStream(stream);
try{
String action = in.readUTF();
switch(action){
case "findPlugins" -> sendPluginMessage("hasPlugin", plugin.serverName());
case "parsePlaceholder" -> {
UUID playerUuid = UUID.fromString(in.readUTF());
String text = in.readUTF();
if(!Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){
sendPluginMessage("parsed", playerUuid.toString(), text);
return;
}
OfflinePlayer targetPlayer = Bukkit.getOfflinePlayer(playerUuid);
String parsed = PlaceholderAPI.setPlaceholders(targetPlayer, text);
sendPluginMessage("parsed", playerUuid.toString(), parsed);
}
default -> plugin.getLogger().warning("Received unknown plugin Message sub channel: " + action);
}
}catch(Exception ex){
plugin.getLogger().log(Level.WARNING, "Encountered an Exception while handling a plugin message.", ex);
}
}
private void sendPluginMessage(String channel, String... values){
plugin.waitUntil(
() -> !Bukkit.getOnlinePlayers().isEmpty() && plugin.serverName() != null,
() -> {
Player plmSender = Bukkit.getOnlinePlayers().iterator().next();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(outStream);
try{
dataOut.writeUTF(channel);
for(String value : values){
dataOut.writeUTF(value);
}
}catch(Exception ex){
plugin.getLogger().log(Level.WARNING, "Encountered an Exception while writiing data for plugin message.", ex);
}
plmSender.sendPluginMessage(plugin, plugin.pluginChannel(), outStream.toByteArray());
}
);
}
}
@@ -0,0 +1,34 @@
package ch.andre601.placeholderapi.messenger;
import ch.andre601.placeholderapi.ASLPlaceholderAPI;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.logging.Level;
public class BungeeCordMessageListener implements PluginMessageListener{
private final ASLPlaceholderAPI plugin;
public BungeeCordMessageListener(ASLPlaceholderAPI plugin){
this.plugin = plugin;
}
@Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message){
if(!channel.equals("BungeeCord"))
return;
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(message));
try{
String subChannel = stream.readUTF();
if("GetServer".equals(subChannel))
plugin.serverName(stream.readUTF());
}catch(Exception ex){
plugin.getLogger().log(Level.WARNING, "Encountered Exception while reading plugin message from Bungeecord channel.", ex);
}
}
}
@@ -0,0 +1,10 @@
name: ASL-PlaceholderAPI
version: '${plugin.version}'
main: ch.andre601.placeholderapi.ASLPlaceholderAPI
api-version: '1.21'
dependencies:
server:
PlaceholderAPI:
load: BEFORE
authors: [ Andre601 ]
description: Addon to allow PlaceholderAPI placeholders on your Velocity/BungeeCord proxy.
@@ -26,8 +26,9 @@
package ch.andre601.advancedserverlist.bungeecord;
import ch.andre601.advancedserverlist.bungeecord.commands.CmdAdvancedServerList;
import ch.andre601.advancedserverlist.bungeecord.listeners.JoinEvent;
import ch.andre601.advancedserverlist.bungeecord.listeners.PingEvent;
import ch.andre601.advancedserverlist.bungeecord.listeners.JoinListener;
import ch.andre601.advancedserverlist.bungeecord.listeners.PingListener;
import ch.andre601.advancedserverlist.bungeecord.listeners.PluginMessageListener;
import ch.andre601.advancedserverlist.bungeecord.logging.BungeeLogger;
import ch.andre601.advancedserverlist.bungeecord.objects.placeholders.BungeePlayerPlaceholders;
import ch.andre601.advancedserverlist.bungeecord.objects.placeholders.BungeeProxyPlaceholders;
@@ -35,9 +36,12 @@ import ch.andre601.advancedserverlist.bungeecord.objects.placeholders.BungeeServ
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.objects.PluginMessageUtil;
import ch.andre601.advancedserverlist.core.profiles.handlers.FaviconHandler;
import com.alessiodp.libby.BungeeLibraryManager;
import com.alessiodp.libby.Library;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import de.myzelyam.api.vanish.BungeeVanishAPI;
import net.kyori.adventure.platform.bungeecord.BungeeAudiences;
import net.md_5.bungee.api.Favicon;
@@ -60,6 +64,8 @@ import java.util.logging.Level;
public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
public static final String ASL_PLUGIN_CHANNEL = "advancedserverlist:action";
private final PluginLogger logger = new BungeeLogger(this);
private final Map<String, ServerPing> fetchedServers = new ConcurrentHashMap<>();
@@ -111,8 +117,9 @@ public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
@Override
public void loadEvents(){
new JoinEvent(this);
new PingEvent(this);
new JoinListener(this);
new PingListener(this);
new PluginMessageListener(this);
}
@Override
@@ -241,11 +248,17 @@ public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
private void fetchServers(){
fetchedServers.clear();
PluginMessageUtil.get().clear();
getProxy().getServers().forEach((name, server) -> server.ping((ping, throwable) -> {
if(throwable != null)
return;
fetchedServers.put(name, ping);
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("findPlugins");
server.sendData(ASL_PLUGIN_CHANNEL, out.toByteArray());
}));
}
}
@@ -32,19 +32,20 @@ import ch.andre601.advancedserverlist.bungeecord.BungeeCordCore;
import ch.andre601.advancedserverlist.bungeecord.objects.impl.BungeePlayerImpl;
import ch.andre601.advancedserverlist.bungeecord.objects.impl.BungeeProxyImpl;
import ch.andre601.advancedserverlist.core.compat.maintenance.MaintenanceUtil;
import ch.andre601.advancedserverlist.core.compat.papi.PAPIUtil;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.interfaces.events.GenericEventWrapper;
import ch.andre601.advancedserverlist.core.objects.CachedPlayer;
import ch.andre601.advancedserverlist.core.objects.PluginMessageUtil;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ProxyPingEvent;
import java.net.InetSocketAddress;
@@ -174,25 +175,25 @@ public class BungeeEventWrapper implements GenericEventWrapper<Favicon, BungeePl
@Override
public String parsePAPIPlaceholders(String text, BungeePlayerImpl player){
if(plugin.getProxy().getPluginManager().getPlugin("PAPIProxyBridge") == null)
return text;
if(!PAPIUtil.get().isCompatible())
return text;
String server = PAPIUtil.get().getServer();
if(server == null || server.isEmpty())
return text;
ServerInfo serverInfo = plugin.getProxy().getServerInfo(server);
if(serverInfo == null || serverInfo.getPlayers().isEmpty())
return text;
ProxiedPlayer carrier = PAPIUtil.get().getPlayer(serverInfo.getPlayers());
if(carrier == null)
return text;
return PAPIUtil.get().parse(text, carrier.getUniqueId(), player.getUUID());
return PluginMessageUtil.get().getOrExecute(player.getUUID().toString(), text, (uuid, textValue) -> {
List<String> servers = PluginMessageUtil.get().getKnownServers();
if(servers.isEmpty())
return textValue;
ServerInfo serverInfo = plugin.getProxy().getServerInfo(servers.get(0));
if(serverInfo == null)
return textValue;
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("parse");
out.writeUTF(uuid);
out.writeUTF(textValue);
serverInfo.sendData(BungeeCordCore.ASL_PLUGIN_CHANNEL, out.toByteArray());
PluginMessageUtil.get().queue(uuid, textValue, false);
return PluginMessageUtil.get().getOrDefault(uuid, textValue);
});
}
@Override
@@ -34,10 +34,10 @@ import net.md_5.bungee.event.EventHandler;
import java.net.InetSocketAddress;
public class JoinEvent implements Listener{
public class JoinListener implements Listener{
private final BungeeCordCore plugin;
public JoinEvent(BungeeCordCore plugin){
public JoinListener(BungeeCordCore plugin){
this.plugin = plugin;
plugin.getProxy().getPluginManager().registerListener(plugin, this);
}
@@ -33,11 +33,11 @@ import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
public class PingEvent implements Listener{
public class PingListener implements Listener{
private final BungeeCordCore plugin;
public PingEvent(BungeeCordCore plugin){
public PingListener(BungeeCordCore plugin){
this.plugin = plugin;
plugin.getProxy().getPluginManager().registerListener(plugin, this);
}
@@ -0,0 +1,37 @@
package ch.andre601.advancedserverlist.bungeecord.listeners;
import ch.andre601.advancedserverlist.bungeecord.BungeeCordCore;
import ch.andre601.advancedserverlist.core.objects.PluginMessageUtil;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
public class PluginMessageListener implements Listener{
public PluginMessageListener(BungeeCordCore plugin){
plugin.getProxy().getPluginManager().registerListener(plugin, this);
}
@EventHandler
public void onPluginMessage(PluginMessageEvent event){
if(!event.getTag().equals(BungeeCordCore.ASL_PLUGIN_CHANNEL))
return;
ByteArrayDataInput input = ByteStreams.newDataInput(event.getData());
String subChannel = input.readUTF();
switch(subChannel){
case "hasPlugin" -> {
String serverName = input.readUTF();
PluginMessageUtil.get().addServer(serverName);
}
case "parsed" -> {
String uuid = input.readUTF();
String parsed = input.readUTF();
PluginMessageUtil.get().queue(uuid, parsed, true);
}
}
}
}
@@ -28,7 +28,7 @@ package ch.andre601.advancedserverlist.core.check;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.interfaces.commands.CmdSender;
import ch.andre601.advancedserverlist.core.objects.ValueCache;
import ch.andre601.advancedserverlist.core.objects.CacheUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -59,7 +59,7 @@ public class UpdateChecker{
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new UpdateCheckThread());
private final ValueCache<CompletableFuture<ModrinthVersion>> cache = new ValueCache<>(Duration.ofMinutes(5));
private final CacheUtil.SingletonCache<CompletableFuture<ModrinthVersion>> cache = new CacheUtil.SingletonCache<>(Duration.ofMinutes(5));
private final AdvancedServerList<?> core;
private final PluginLogger logger;
@@ -441,7 +441,7 @@ public class CommandHandler{
.appendText("|")
.appendSpace()
// list
.appendLiteralArgument("list", "Lists all currently know profiles and wether they are valid or not.")
.appendLiteralArgument("list", "Lists all currently know profiles and whether they are valid or not.")
// Closing bracket
.appendText("></grey>")
.build();
@@ -32,7 +32,7 @@ public class CommandStringBuilder{
private final List<CommandPart> commandParts = new ArrayList<>();
public CommandStringBuilder(String subcommand, String description){
appendText("<hover:show_text:\"<grey>" + description + "</grey>\"><white>" + subcommand + "</white></hover>");
appendLiteralArgument(subcommand, description);
}
public CommandStringBuilder appendArgument(Argument argument){
@@ -1,92 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2023 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.compat.papi;
import ch.andre601.advancedserverlist.core.objects.ValueCache;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import net.william278.papiproxybridge.api.PlaceholderAPI;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class PAPIUtil{
private static PAPIUtil instance;
private final ValueCache<CompletableFuture<Set<String>>> serversCache = new ValueCache<>(Duration.ofSeconds(10));
private final Cache<UUID, CompletableFuture<String>> textCache = CacheBuilder.newBuilder()
.expireAfterWrite(Duration.ofSeconds(10))
.build();
private final PlaceholderAPI papi;
private PAPIUtil(){
this.papi = PlaceholderAPI.createInstance();
}
public static PAPIUtil get(){
if(instance != null)
return instance;
return (instance = new PAPIUtil());
}
// Make sure the version of PAPIProxyBridge we get has the required methods we need...
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isCompatible(){
try{
papi.getClass().getMethod("getServers");
return true;
}catch(NoSuchMethodException ex){
return false;
}
}
public String getServer(){
Set<String> values = serversCache.get(papi::getServers).getNow(Collections.emptySet());
if(values.isEmpty())
return null;
return List.copyOf(values).get(0);
}
public <P> P getPlayer(Collection<P> players){
if(players.isEmpty())
return null;
return List.copyOf(players).get(0);
}
public String parse(String text, UUID carrier, UUID player){
try{
return textCache.get(player, () -> papi.formatPlaceholders(text, carrier, player)).getNow(text);
}catch(ExecutionException ex){
return text;
}
}
}
@@ -26,25 +26,58 @@
package ch.andre601.advancedserverlist.core.objects;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class ValueCache<T>{
public abstract class CacheUtil{
private final Duration duration;
private CacheValue<T> cache = null;
protected final Duration duration;
public ValueCache(Duration duration){
public CacheUtil(Duration duration){
this.duration = duration;
}
public T get(Supplier<T> supplier){
if(cache == null || cache.expired())
cache = new CacheValue<>(System.currentTimeMillis(), duration, supplier.get());
public static class SingletonCache<T> extends CacheUtil{
return cache.value();
private CacheValue<T> cacheValue = null;
public SingletonCache(Duration duration){
super(duration);
}
public T get(Supplier<T> supplier){
if(cacheValue == null || cacheValue.expired())
cacheValue = new CacheValue<>(System.currentTimeMillis(), duration, supplier.get());
return cacheValue.value();
}
}
private record CacheValue<T>(long timestamp, Duration duration, T value){
public static class IdentifiableCache<K, V> extends CacheUtil{
private final Map<K, CacheValue<V>> cacheValues = new HashMap<>();
public IdentifiableCache(Duration duration){
super(duration);
}
public V get(K key, Supplier<V> supplier){
CacheValue<V> value = cacheValues.get(key);
if(value == null || value.expired()){
value = new CacheValue<>(System.currentTimeMillis(), duration, supplier.get());
cacheValues.put(key, value);
}
return cacheValues.get(key).value();
}
public void clear(){
cacheValues.clear();
}
}
public record CacheValue<T>(long timestamp, Duration duration, T value){
public boolean expired(){
return (timestamp < 0L) || System.currentTimeMillis() - timestamp >= duration.toMillis();
}
@@ -0,0 +1,57 @@
package ch.andre601.advancedserverlist.core.objects;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiFunction;
public class PluginMessageUtil{
private static PluginMessageUtil instance;
private final List<String> knownServers = new CopyOnWriteArrayList<>();
private final Map<String, ParsedText> text = new ConcurrentHashMap<>();
private PluginMessageUtil(){}
public static PluginMessageUtil get(){
if(instance != null)
return instance;
return (instance = new PluginMessageUtil());
}
public void addServer(String name){
this.knownServers.add(name);
}
public List<String> getKnownServers(){
return knownServers;
}
public void clear(){
knownServers.clear();
}
public String getOrExecute(String key, String value, BiFunction<String, String, String> function){
if(text.get(key) != null){
return getOrDefault(key, value);
}
return function.apply(key, value);
}
public void queue(String key, String value, boolean parsed){
text.put(key, new ParsedText(value, parsed));
}
public String getOrDefault(String key, String def){
if(text.get(key) == null)
return def;
return text.get(key).parsed() ? text.remove(key).text() : text.get(key).text();
}
private record ParsedText(String text, boolean parsed){}
}
@@ -27,8 +27,7 @@ package ch.andre601.advancedserverlist.core.profiles.handlers;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import ch.andre601.advancedserverlist.core.objects.CacheUtil;
import javax.imageio.ImageIO;
import java.awt.*;
@@ -42,9 +41,13 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
public class FaviconHandler<F>{
@@ -52,7 +55,7 @@ public class FaviconHandler<F>{
private final AdvancedServerList<F> core;
private final PluginLogger logger;
private final ThreadPoolExecutor faviconThreadPool;
private final Cache<String, CompletableFuture<F>> faviconCache;
private final CacheUtil.IdentifiableCache<String, CompletableFuture<F>> faviconCache;
private final Map<String, F> localFavicons = new HashMap<>();
private final HttpClient client = HttpClient.newHttpClient();
@@ -62,42 +65,32 @@ public class FaviconHandler<F>{
this.core = core;
this.logger = core.getPlugin().getPluginLogger();
this.faviconThreadPool = createFaviconThreadPool();
this.faviconCache = CacheBuilder.newBuilder()
.expireAfterWrite(core.getFileHandler().getLong(1, 1, "faviconCacheTime"), TimeUnit.MINUTES)
.build();
this.faviconCache = new CacheUtil.IdentifiableCache<>(Duration.ofMinutes(
core.getFileHandler().getLong(1, 1, "faviconCacheTime")
));
loadLocalFavicons();
}
public F getFavicon(String input){
if(localFavicons.size() > 0){
if(!localFavicons.isEmpty()){
logger.debug(FaviconHandler.class, "Current Local Favicons:");
for(String key : localFavicons.keySet()){
logger.debug(FaviconHandler.class, " - %s", key);
}
}
if(input.equalsIgnoreCase("random")){
logger.debug(FaviconHandler.class, "Input matches 'random'. Returning random Favicon...");
return getRandomized();
}
if(localFavicons.containsKey(input.toLowerCase(Locale.ROOT))){
logger.debug(FaviconHandler.class, "Input matches local favicon Image. Returning it...");
return localFavicons.get(input.toLowerCase(Locale.ROOT));
}
try{
logger.debug(FaviconHandler.class, "Getting Favicon image from cache...");
return faviconCache.get(input, () -> getFuture(input)).getNow(null);
}catch(ExecutionException ex){
logger.warn("Received ExecutionException while retrieving Favicon for '<white>%s</white>'.", ex, input);
return null;
}
logger.debug(FaviconHandler.class, "Getting Favicon image from cache...");
return faviconCache.get(input, () -> getFuture(input)).getNow(null);
}
public void cleanCache(){
faviconCache.invalidateAll();
faviconCache.clear();
loadLocalFavicons();
}
@@ -113,7 +106,7 @@ public class FaviconHandler<F>{
logger.debug(FaviconHandler.class, "Resolving image file '%s'...", input);
return CompletableFuture.completedFuture(localFavicons.get(input.toLowerCase(Locale.ROOT)));
}else{
logger.debug(FaviconHandler.class, "Resolving Name/UUID as https://mc-heads.net/avatar/%s/64...", input);
logger.debug(FaviconHandler.class, "Resolving '%s' as 'https://mc-heads.net/avatar/%s/64'...", input, input);
return CompletableFuture.supplyAsync(() -> fromURL(core, "https://mc-heads.net/avatar/" + input + "/64"), this.faviconThreadPool);
}
}
+183
View File
@@ -0,0 +1,183 @@
---
icon: octicons/plus-circle-24
---
AdvancedServerList allows you to add your own Placeholders to be useable through its `${identifier value}` format.
The benefit of this method over alternatives such as using PlaceholderAPI placeholders is availability and the fact that these placeholders can be used within the [`condition` option](../profiles/index.md#condition) of the plugin.
Adding your own placeholder is relatively easy and only requires the main API module to be used in your dependencies, unless you need platform-specific values (Explained later on).
## Create your PlaceholderProvider class
AdvancedServerList's placeholder system uses a dedicated [`PlaceholderProvider`](reference/api/ch.andre601.advancedserverlist.api/placeholderprovider.md) class where the placeholder gets defined and its values parsed.
In order to add your own, you'll need to first create a new class and make it extend the `PlaceholderProvider` class:
```java title="MyPlaceholder.java"
public class MyPlaceholder extends PlaceholderProvider {
}
```
Your IDE should now report issues, namely a missing method to override and a missing Constructor to match the extended class' one. Your IDE should allow you to easily implement those, if not, then manually add the constructor with a `String` argument and the `public String parsePlaceholder` method with `String`, [`GenericPlayer`](reference/api/ch.andre601.advancedserverlist.api/objects/genericplayer.md) and [`GenericServer`](reference/api/ch.andre601.advancedserverlist.api/objects/genericserver.md) arguments:
```java { title="MyPlaceholder.java" .annotate }
public class MyPlaceholder extends PlaceholderProvider {
public MyPlaceholder(String identifier) {
super(identifier); // (1)
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server) {
return null;
}
}
```
1. It is recommended to replace the Constructor with a No-Args Constructor and set the placeholder name directly in the `super` call:
```java
public MyPlaceholder() {
super("myplaceholder");
}
```
## Parsing placeholders
To now parse your placeholders, all you need to do is edit the `parsePlaceholder` method.
AdvancedServerList calls this method whenever it finds a matching identifier of a PlaceholderProvider, with the `String` argument being the actual value after the identifier and the `GenericPlayer` and `GenericServer` arguments holding the Player and server values respectively.
As an example, assuming you simply want to return `Hello` for the placeholder `${myplaceholder sayHello}`, this would be the code for it:
```java { title="MyPlaceholder.java" .annotate }
public class MyPlaceholder extends PlaceholderProvider {
public MyPlaceholder() {
super("myplaceholder");
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server) {
if (placeholder.equals("sayHello")) {
return "Hello";
}
return null; // (1)
}
}
```
1. Returning `null` tells AdvancedServerList that the placeholder was invalid, making it return the placeholder unchanged, while also reporting an error, if used in `condition`.
## Registering the Placeholder
The final step now would be to register your placeholder for AdvancedServerList to use.
To do this, obtain an instance of the [`AdvancedServerListAPI`](reference/api/ch.andre601.advancedserverlist.api/advancedserverlistapi.md) through its static `get()` method and then call `addPlaceholderProvider(PlaceholderProvider)` through it:
/// tab | :fontawesome-solid-paper-plane: Paper Example
```java title="MyPlugin.java"
public class MyPlugin extends JavaPlugin {
@Override
public void onEnable() {
AdvancedServerListAPI api = AdvancedServerListAPI.get();
api.addPlaceholderProvider(new MyPlaceholder());
getLogger().info("Hooked into AdvancedServerList!");
}
}
```
///
/// tab | :octicons-git-merge-24: BungeeCord Example
```java title="MyPlugin.java"
public class MyPlugin extends Plugin {
@Override
public void onEnable() {
AdvancedServerListAPI api = AdvancedServerListAPI.get();
api.addPlaceholderProvider(new MyPlaceholder());
getLogger().info("Hooked into AdvancedServerList!");
}
}
```
///
/// tab | :fontawesome-solid-paper-plane: Velocity Example
```java title="MyPlugin.java"
@Plugin(
id = "myplugin",
version = "1.0.0",
authors = {"You?"},
dependencies = {
@Dependency(id = "advancedserverlist")
}
)
public class MyPlugin {
private final ProxyServer proxy;
private final Logger logger;
@Inject
public MyPlugin(ProxyServer proxy, Logger logger) {
this.proxy = proxy;
this.logger = logger;
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
AdvancedServerListAPI api = AdvancedServerListAPI.get();
api.addPlaceholderProvider(new MyPlaceholder());
logger.info("Hooked into AdvancedServerList!");
}
}
```
///
## You're done
Your Placeholders should now be registered successfully if they check the following:
- The provided identifier is not `null` nor empty.
- The provided identifier does not contain spaces.
- The provided identifier is not already registered in the API.
## Note on `GenericPlayer` and `GenericServer`
The different platform APIs of AdvancedServerList provide extended versions of the `GenericPlayer` and `GenericServer` instances used, providing additional methods otherwise not available.
Should you want to use these specific instances will you need to add the platform API as an additional dependency to your project and then cast the `GenericPlayer` and/or `GenericServer` instance to the platform specific version.
Below is an example using the `platform-bukkit` API (This assumes your plugin is one running on Paper):
```java { title="MyPlaceholder.java" .annotate }
public class MyPlaceholder extends PlaceholderProvider {
public MyPlaceholder() {
super("myplaceholder");
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server) {
if (!(player instanceof BukkitPlayer bukkitPlayer)) {
return null; // (1)
}
return switch (placeholder) {
case "playedBefore" -> String.valueOf(bukkitPlayer.hasPlayedBefore());
case "whitelisted" -> String.valueOf(bukkitPlayer.isWhitelisted());
case "banned" -> String.valueOf(bukkitPlayer.isBanned());
default -> null;
};
}
}
```
1. Depending on the Java version you use will you need to alter the code:
```java
if (!(player instanceof BukkitPlayer)) {
return null;
}
// You need to cast it separately.
BukkitPlayer bukkitPlayer = (BukkitPlayer) player;
// ...use bukkitPlayer here.
```
+7 -111
View File
@@ -84,127 +84,23 @@ dependencies {
```
///
## Adding your own Placeholders
## Tutorials
<!-- admo:info This requires the main api module -->
Dedicated pages to explain aspects of the API are available:
The API allows you to add your own placeholders which would be available through the `${<identifier> <values>}` placeholder Pattern in a Server List profile.
<div class="grid cards" markdown>
To add your own placeholders, follow these steps:
- [:octicons-plus-circle-24: Adding Placeholders](adding-placeholders.md)
- [:octicons-broadcast-24: Listening for Events](listening-for-events.md)
### 1. Create a Placeholder class
</div>
You should first create a new class and make it extend the abstract [`PlaceholderProvider`][placeholderprovider]. This class includes a constructor and a method you need to add, so do that:
```java { .annotate title="Creating PlaceholderProvider class" }
public class MyPlaceholders extends PlaceholderProvider {
public MyPlaceholders(String identifier) {
super(identifier); // (1)
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server) {
return null;
}
}
```
1. It is recommended to replace this constructor with a no-args Constructor and have the placeholder name set in the `super` directly:
```java
public MyPlaceholders() {
super("myplaceholders");
}
```
The [`parsePlaceholder(String, GenericPlayer, GenericServer)`][parseplaceholder] method is used by AdvancedServerList to replace a matching placeholder with a value.
What you return is completely up to you. Just keep in mind that returning `null` will be treated as an invalid placeholder by AdvancedServerList, resulting in the placeholder being returned as-is without any changes.
[placeholderprovider]: reference/api/ch.andre601.advancedserverlist.api/placeholderprovider.md
[parseplaceholder]: reference/api/ch.andre601.advancedserverlist.api/placeholderprovider.md#parseplaceholder(string,-genericplayer,-genericserver)
/// details | Example of final class
type: example
```java title="MyPlaceholders.java"
public class MyPlaceholders extends PlaceholderProvider {
public MyPlaceholders() {
super("myplaceholders");
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server) {
if(placeholder.equalsIgnoreCase("hello"))
return "Hello " + player.getName();
return null;
}
}
```
///
### 2. Register the Placeholders
Next step should be to register the placeholder. To achieve this, first obtain an instance of the [`AdvancedServerListAPI`][advancedserverlistapi] by using the static [`get()`][get] method. After that call [`addPlaceholderProvider(PlaceholderProvider placeholderProvider)`][addplaceholderprovider].
Your code may look similar to this:
```java title="Registering PlaceholderProvider class"
public class MyPlugin extends JavaPlugin {
@Override
public void onEnable() {
AdvancedServerListAPI api = AdvancedServerListAPI.get();
api.addPlaceholderProvider(new MyPlaceholders());
}
}
```
[advancedserverlistapi]: reference/api/ch.andre601.advancedserverlist.api/advancedserverlistapi.md
[get]: reference/api/ch.andre601.advancedserverlist.api/advancedserverlistapi.md#get()
[addplaceholderprovider]: reference/api/ch.andre601.advancedserverlist.api/advancedserverlistapi.md#addplaceholderprovider(placeholderprovider)
This should register your PlaceholderExpansion as long as it is valid, meaning that the identifier...
- ...is not `null`
- ...is not containing spaces
- ...is not using a name already registered in the API
### 3. Declare AdvancedServerList as (soft)depend
## Declare AdvancedServerList as (soft)depend
The final thing you should make sure is to define AdvancedServerList as a depend or soft-depend for your plugin, to make sure it loads after AdvancedServerList.
Below are example setups for Spigot, Paper, BungeeCord and Velocity:
/// tab | :simple-spigotmc: Spigot
//// tab | Softdepend
```yaml title="plugin.yml"
name: "MyPlugin"
author: "author"
version: "1.0.0"
main: "com.example.plugin.ExamplePlugin"
softdepend:
- AdvancedServerList
```
////
//// tab | Depend
```yaml title="plugin.yml"
name: "MyPlugin"
author: "author"
version: "1.0.0"
main: "com.example.plugin.ExamplePlugin"
depend:
- AdvancedServerList
```
////
///
/// tab | :fontawesome-solid-paper-plane: Paper
//// tab | Softdepend
```yaml title="paper-plugin.yml"
+65
View File
@@ -0,0 +1,65 @@
---
icon: octicons/broadcast-24
---
AdvancedServerList provides some events that your plugin can listen to.
These events are structurally the same across all platforms, yet still require the usage of Platform-specific APIs due to how some events are registered and handled on some platforms.
The plugin currently offers the following events:
<div class="grid cards" markdown>
- [PreServerListSetEvent](#preserverlistsetevent)
- [PostServerListSetEvent](#postserverlistsetevent)
</div>
## PreServerListSetEvent
This event is executed before AdvancedServerList tries to modify the player list.
### Methods { #preserverlistsetevent-methods }
The following methods are available to use:
| Method | Description |
|--------------------------|--------------------------------------------------------------------------------|
| `getEntry()` | Returns the [`ProfileEntry`][profileentry] that AdvancedServerList should use. |
| `setEntry(ProfileEntry)` | Sets the [`ProfileEntry`][profileentry] that should be used. |
| `isCancelled()` | Returns wether this event was cancelled or not. |
| `setCancelled(boolean)` | Sets the event's cancelled state. |
### Notes { #preserverlistsetevent-notes }
- Providing `null` as the `ProfileEntry` for `setEntry(ProfileEntry)` is not allowed. Also, a copy of the provided `ProfileEntry` is made and used.
## PostServerListSetEvent
This event is executed after AdvancedServerList completed the server list modifications.
### Methods { #postserverlistsetevent-methods }
| Method | Description |
|--------------------------|--------------------------------------------------------------------------|
| `getEntry()` | Returns the [`ProfileEntry`][profileentry] that AdvancedServerList used. |
### Notes { #postserverlistsetevent-notes }
- The returned `ProfileEntry` is not an actual representation of what is being displayed to the player and rather an instance of values the plugin received.
The returned value may also be `null` should the Ping Event be cancelled due to things such as an invalid Protocol or the [`PreServerListSetEvent`](#preserverlistsetevent) being cancelled.
## Registering the Events
To register an event, please refer to our platforms documentation on how to do this.
## What is a ProfileEntry?
Both events provide and use a so called [`ProfileEntry`][profileentry].
The `ProfileEntry` is a record, representing the values of a [Server List Profile](../profiles/index.md), meaning all values you can set in the profile configuration (Except condition and priority) will be available as a `ProfileEntry`.
It is important to note, that the `ProfileEntry` can be a representation of the [`profiles` option](../profiles/index.md#profiles), the global options or a mixture of both.
If you want to create your own instance, you'll need to use the [`ProfileEntry.Builder` class](reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md) as the `ProfileEntry` is unmodifiable.
A convenience method in the form of `builder()` exists to create a Builder instance of the ProfileEntry with its values already pre-set.
[profileentry]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/index.md
+2 -6
View File
@@ -113,6 +113,8 @@ AdvancedServerList supports the following platforms:
**Other Pages:**
- [:octicons-plus-circle-24: Adding Placeholders](api/adding-placeholders.md)
- [:octicons-broadcast-24: Listening for Events](api/listening-for-events.md)
- [:octicons-log-24: Changelog](api/changelog.md)
- [:octicons-link-external-24: Javadocs](api/javadocs.md)
- [:simple-codeberg: Source Code](api/source.md)
@@ -129,11 +131,5 @@ AdvancedServerList supports the following platforms:
**Other Pages:**
- [:octicons-stop-24: BanPlugins Addon](addons/banplugins.md)
- [:material-percent: **PlaceholderAPI**](placeholderapi/index.md)
----
Information about available placeholders to use in PlaceholderAPI and how to use placeholders from other plugins in AdvancedServerList using PlaceholderAPI.
</div>
+86 -47
View File
@@ -4,69 +4,108 @@ icon: octicons/pencil-24
# Formatting
AdvancedServerList utilizes the [MiniMessage] text formatting to allow colors, formatting codes, gradients, etc. for the text options `motd`, `playerCount -> hover` and `playerCount -> text`.
You can find a collection of available tags on the library's [Format] page. Please make sure to see the [Unsupported Formatting](#unsupported-formatting) section below for tags with no support.
This page explains specific points of formatting in AdvancedServerList, be it [text formatting](#text-formatting) or special quirks of [YAML formatting](#yaml-formatting).
If you have questions, don't hesitate to join the [M.O.S.S. Discord][discord] and ask in the `#asl-support` channel.
## Why no legacy colors (`&`/`§` codes) support?
## Text Formatting
### The tl;dr
AdvancedServerList uses the [MiniMessage Text Formatting][minimessage] for all formatting of text options ([`motd`](index.md#motd), [`playerCount -> hover`](index.md#hover) and [`playerCount -> text`](index.md#text)).
It supports all available [formatting tags][tags] with a [few exceptions and limitations](#exceptions-and-limitations).
MiniMessage tags are overall more readable while also allowing a lot more ways of formatting, with Legacy colors becoming an unreadable mess the more complex your formatting is.
### The long explanation
Legacy colors are a mess to read. This becomes especially evident with gradients using RGB color support.
As an example is here the text `Hello World` made into a Gradient with starting color `#084CFB` and end color `#ADF3FD` both in Legacy Color (Using `&` character) and MiniMessage format:
/// tab | Legacy Color Codes
```
&#084CFBH&#195DFBe&#296DFBl&#3A7EFCl&#4A8FFCo &#6BB0FCW&#7CC1FCo&#8CD2FDr&#9DE2FDl&#ADF3FDd
```
/// note
Please note that the available tags in MiniMessage depend heavily on the version used on the Server or Proxy.
While AdvancedServerList downloads MiniMessage for BungeeCord, is it using the built-in version on Paper and Velocity. Due to this could the version used be older than the one the plugin is compiled against.
///
/// tab | MiniMessage
```
<gradient:#084CFB:#ADF3FD>Hello World</gradient>
```
///
[minimessage]: https://docs.advntr.dev/minimessage/index.html
[tags]: https://docs.advntr.dev/minimessage/format.html
This becomes even more difficult to work with if you want to add text formatting to only parts of the text.
Assuming you want to make `World` be bold, with legacy colors, you would need to add `&l` before every character of the word, as colors reset any formatting applied. In MiniMessage all you need to do is put `<bold>` before the word and `</bold>` after it.
### Why MiniMessage and not `&`/`§`? { #why-minimessage }
Another benefit for gradients in particular is, that MiniMessage allows more than one color to be set for the gradient, i.e. you can set three colors for a start, middle and end color.
The reason to only support MiniMessage and not the so-called legacy color and formatting codes can be boiled down to 3 specific reasons:
## Web Editor
1. **MiniMessage tags are more clear on what they do.**
`<aqua>` makes it clear that it colors the text while `&b` is not as clear on that matter.
2. **MiniMessage allows easier combination of color and formatting codes.**
MiniMessage "remembers" what colors and formatting you applied, meaning if you close a tag and a previous one was set before it, that will continue.
/// details | Example
type: example
Below is a comparison of the same text made in MiniMessage and Color codes.
//// tab | MiniMessage
```
<aqua>Hello <green><bold>World! <red>How</bold> are</red> you?
```
////
//// tab | Color Codes
```
# We add &c after "How" to avoid a "bold space"
&bHello &a&lWorld! &c&lHow&c are &ayou?
```
////
///
3. **MiniMessage adds easier support for advanced features (RGB colors, gradients, etc.)**
With MiniMessage is it significantly more easy to use more advanced features such as gradients, rgb colors and similar.
While legacy colors have a form of RGB support is the format weird to look at and gradients become a mess. This is even worse when including bold for specific characters.
/// details | Example
type: example
Below is an example of a Gradient starting at `#084CFB` (:octicons-dot-fill-24:{ style="color: #084CFB;" }) and ending at `#ADF3FD` (:octicons-dot-fill-24:{ style="color: #ADF3FD;" }).
//// tab | MiniMessage
```
<gradient:#084CFB:#ADF3FD>Hello World!</gradient>
```
////
//// tab | Color Codes
```
&#084CFBH&#195DFBe&#296DFBl&#3A7EFCl&#4A8FFCo &#6BB0FCW&#7CC1FCo&#8CD2FDr&#9DE2FDl&#ADF3FDd
```
////
///
The Adventure team offers an [Online Web tool][webviewer]{ target="_blank" rel="nofollow" } that allows you to create the right MiniMessage tags while also having a preview.
Just visit the page and make sure to select `Server List` at the top to have a preview in a server list.
In general is MiniMessage a lot easier to manage and read as legacy color codes, as their appearance is more distinct from normal text.
## YAML Formatting
### Exceptions and Limitations
It is recommended to always surround your text with single or double quotes. This avoids situations where the YAML parses sees a specific character and treats it as a special YAML feature.
This is especially the case with MiniMessage tags, where `<` can be seen as the start of a so-called scolar value.
Due to the situation MiniMessage is used in are not all of its features available to use.
Below is a list of all features that cannot be used by AdvancedServerList, or can only be used by it under specific conditions.
Should you be using single quotes inside the text itself - i.e. for words such as `you're` - will you either need to surround the text with double quotes, or change the single quote in the word to two single quotes (`you're` becomes `you''re`).
| Feature | Tag | Supported? |
|---------------|------------------------------|------------------------------------------------------------------------------------------------------------------------------------|
| RGB Colors | `<#rrggbb>` | Only works properly on `motd` and will be downsampled to the closest named color for the other options. |
| RGB Gradients | `<gradient:#rrggbb:#rrggbb>` | Only works properly on `motd` and will be downsampled to the closest named color for the other options. |
| Click Actions | `<click:_type_:_value_>` | Tag will be rendered, but clicking the text won't do anything. |
| Hover Actions | `<hover:_type_:_value_>` | Tag will be rendered, but hovering the text won't show anything. |
| Insertions | `<insertion:_value_>` | Tag will be rendered, but clicking the text won't do anything. |
| Font | `<font:_font_>` | May work with the default fonts (`default`, `alt` and `uniform`) and with custom ones should the client already have it. |
| Selector | `<selector:_sel_>` | Tag will be rendered, but clicking the text won't do anything. |
| Score | `<score:_name_:_objective_>` | Will not render due to requiring the player to be on the server. |
| Pride | `<pride[:_flag_]>` | Only works if the server (Paper) or Proxy (Velocity) use `v4.18.0` of MiniMessage. BungeeCord is unaffected due to downloading it. |
## Unsupported Formatting
## Yaml Formatting
### Non-functional Tags
YAML has some special quirks that require attention when editing the file.
Such quirks include features such as...
While MiniMessage will parse most, if not all tags, will not all work.
The following list of tags will do nothing, or only work under specific circumstances:
- Reading `~` and `null` as literal null values.
- Reading `>` and `|` as multi-line indicators.
| Tag | Note |
|---------------|------------------------------------------------------------------------------------------------------|
| `<click>` | |
| `<hover>` | |
| `<insertion>` | |
| `<font>` | May work if either a default MC font is used, or the player has a resourcepack with the font loaded. |
| `<selector>` | |
| `<score>` | |
To avoid this should you always surround text values with single (`'`) or double quotes (`"`) to force the YAML parser to see those as Strings.
### Non-supported RGB
/// note | Note on Single quotes inside text
Using single quotes, the YAML parser may get confused when the text itself also contains a single quote.
As an example `'You're banned'` would mess up the value because the `'` in `You're` is understood as the end of the String.
Only the `motd` option supports RGB colors. Every other option allowing MiniMessage format may only support the default colors provided by Minecraft (`<aqua>`, `<yellow>`, etc) with RGB colors being downsampled to their next supported option.
To avoid this issue, do one of the following:
[MiniMessage]: https://docs.advntr.dev/minimessage/index.html
[Format]: https://docs.advntr.dev/minimessage/format.html
[webviewer]: https://webui.advntr.dev/
- Surround the text with Double quotes instead of Single quotes (`"You're banned"`)
- Use two single quotes (`''`) inside the text every time you want to display a single quote character (`'You''re banned'`)
///
+67 -42
View File
@@ -15,43 +15,39 @@ The following placeholders are available in AdvancedServerList itself. Please no
These placeholders use the player who pinged the server, to return values. They may require the player to be cached in order to work.
| Placeholder | Description | Platforms | Cached Player required?[^1] |
|-----------------------------|-----------------------------------------------------------------|--------------|-----------------------------|
| `${player name}` | The name of the player. | All | Yes[^2] |
| `${player protocol}` | The protocol version of the player. | All | No |
| `${player uuid}` | The UUID of the player. | All | Yes[^3] |
| `${player version}` | The protocol version of the player as readable MC version. | Velocity | No |
| `${player hasPlayedBefore}` | Boolean for whether the player has played on the server before. | Paper | Yes |
| `${player isBanned}` | Boolean for whether the player has been banned from the server. | Paper | Yes |
| `${player isWhitelisted}` | Boolean for whether the player is whitelisted on the server. | Paper | Yes |
| Placeholder | Description | Platforms | Cached Player required?^[1](#player-n1)^ |
|-----------------------------|-----------------------------------------------------------------|--------------|------------------------------------------|
| `${player name}` | The name of the player. | All | Yes^[2](#player-n2)^ |
| `${player protocol}` | The protocol version of the player. | All | No |
| `${player uuid}` | The UUID of the player. | All | Yes^[3](#player-n3)^ |
| `${player version}` | The protocol version of the player as readable MC version. | Velocity | No |
| `${player hasPlayedBefore}` | Boolean for whether the player has played on the server before. | Paper | Yes |
| `${player isBanned}` | Boolean for whether the player has been banned from the server. | Paper | Yes |
| `${player isWhitelisted}` | Boolean for whether the player is whitelisted on the server. | Paper | Yes |
[^1]:
Whether this placeholder requires the player to have joined before while AdvancedServerList was running.
When `disableCache` is enabled will these placeholders not work.
[^2]: Will default to whatever name has been provided in the `unknownPlayer -> name` option of the config.yml, when the player isn't cached yet.
[^3]: Will default to whatever name has been provided in the `unknownPlayer -> uuid` option of the config.yml, when the player isn't cached yet.
<small>^1^{ #player-n1 } When `Yes` is set, requires the player to have joined before while AdvancedServerList was running. Placeholder will not work when `disableCache` is true.</small>
<small>^2^{ #player-n2 } Will default to the value provided in `unknownPlayer -> name` of the config.yml, should the player not be cached yet.</small>
<small>^3^{ #player-n3 } Will default to the value provided in `unknownPlayer -> uuid` of the config.yml, should the player not be cached yet.</small>
### Server
These placeholders use values given by the server/proxy AdvancedServerList runs on.
| Placeholder | Description | Platforms |
|------------------------------|------------------------------------------------------------|-----------|
| `${server playersOnline}` | The number of players online on this proxy/server.[^4] | All |
| `${server playersMax}` | The total number of players that can join this server.[^5] | All |
| `${server host}` | The domain/IP the player pinged.[^6] | All |
| `${server whitelistEnabled}` | Whether the whitelist is enabled or not. | Paper |
| Placeholder | Description | Platforms |
|------------------------------|-------------------------------------------------------------------------|-----------|
| `${server playersOnline}` | The number of players online on this proxy/server.^[1](#server-n1)^ | All |
| `${server playersMax}` | The total number of players that can join this server.^[2](#server-n2)^ | All |
| `${server host}` | The domain/IP the player pinged.^[3](#server-n3)^ | All |
| `${server whitelistEnabled}` | Whether the whitelist is enabled or not. | Paper |
[^4]:
A comma-separated list of world (On Paper) or Server (On BungeeCord/Velocity) names can be provided to display the added numbers of players in these worlds/servers.
**Example:** `${server playersOnline lobby1,lobby2}` will display the collective numbers of players in the servers `lobby1` and `lobby2`.
Using the [onlinePlayers' `amount`](index.md#onlineplayers-amount) option will modify the output of this placeholder, except when used in [`condition`](index.md#condition).
[^5]:
Using either the [extraPlayers' `amount`](index.md#extraplayers-amount) or [maxPlayers' `amount`](index.md#maxplayers-amount) option will make this placeholder return the modified max players count.
Only exception to this rule is when the placeholder is used in the [`condition`](index.md#condition) option in which case it returns the actual max player count of the proxy/server.
[^6]:
An optional server name can be provided to display the IP/Domain associated with that server. This only works on BungeeCord or Velocity.
**Example:** `${server host survival}` would display the IP/Domain associated with the `survival` server.
<small>^1^{ #server-n1 } You can provide a comma-separated list of world or server names (based on platform) to return the collective count of players on these worlds/servers.
Additionally, when using [`playerCount -> onlinePlayers`](index.md#onlineplayers) will this placeholder return the modified online players count, except when used within the [`condition`](index.md#condition) option.</small>
<small>^2^{ #server-n2 } When using either [`playerCount -> extraPlayers`](index.md#extraplayers) or [`playerCount -> maxPlayers`](index.md#maxplayers) will this placeholder return the modified max players count, except when used within the [`condition`](index.md#condition) option.</small>
<small>^3^{ #server-n3 } An optional server name may be provided to display the IP/Domain associated with said server. This only works for the BungeeCord and Velocity version of the plugin.</small>
### Proxy
@@ -61,14 +57,14 @@ These placeholders are only available on the BungeeCord and Velocity versions of
Servers are pinged every 10 seconds by the plugin and cached for that time period.
///
| Placeholders | Description | Default[^7] |
|------------------------------|-------------------------------------------------------------------|-------------|
| `${proxy status <name>}` | Returns `online` or `offline` based on the Server's availability. | `offline` |
| `${proxy motd <name>}` | Returns the Server's MOTD as MiniMessage String. | `none` |
| `${proxy players <name>}` | Returns the number of online Players on the Server. | `0` |
| `${proxy maxPlayers <name>}` | Returns the max number of Players allowed to join the Server. | `0` |
| Placeholders | Description | Default^[1](#proxy-n1)^ |
|------------------------------|-------------------------------------------------------------------|-------------------------|
| `${proxy status <name>}` | Returns `online` or `offline` based on the Server's availability. | `offline` |
| `${proxy motd <name>}` | Returns the Server's MOTD as MiniMessage String. | `none` |
| `${proxy players <name>}` | Returns the number of online Players on the Server. | `0` |
| `${proxy maxPlayers <name>}` | Returns the max number of Players allowed to join the Server. | `0` |
[^7]: The default value returned, should the Server or parts of it not be available.
<small>^1^{ #proxy-n1 } The default value returned, should the Server or parts of it not be available.</small>
### Maintenance
@@ -78,13 +74,42 @@ These placeholders require the [Maintenance](https://hangar.papermc.io/kennytv/M
|-------------------------------------|----------------------------------------------------------------|
| `${maintenance maintenanceEnabled}` | Returns whether the Global maintenance mode is enabled or not. |
## Adding your own Placeholders
Thanks to the API of AdvancedServerList are you able to add your own Placeholders that can be used using the `${identifier value}` pattern.
To learn how to do this, head over to the [API page](../api/index.md) to learn more.
## PlaceholderAPI
Please visit the [PlaceholderAPI page](../placeholderapi/index.md) for how AdvancedServerList works with PlaceholderAPI.
### Own Placeholders
## Custom Placeholders
The Paper version of AdvancedServerList provides the following placeholders to use through PlaceholderAPI.
Since version 2 of AdvancedServerList are developers able to provide their own placeholders to be used in a server list profile.
The format follows the same one as the [built-in placeholders](#built-in-placeholders), meaning it is `${<identifier> <placeholder>}`.
/// info
AdvancedServerList uses the same logic to determine the value to return for a player as it does when selecting a Server List Profile.
///
If you're a developer and want to integrate your own placeholders into AdvancedServerList, read about it [here](../api/index.md).
| Placeholder | Description | Default^[1](#papi-n1)^ |
|--------------------------------------|-----------------------------------------------------------------------------------|------------------------|
| `%asl_favicon%` | Value of `favicon` when present. | `(empty string)` |
| `%asl_motd%` | Value of `motd` when present. | `(empty string)` |
| `%asl_playercount_extraplayers%` | Value of `playerCount -> extraPlayers -> amount`. | `(empty string)` |
| `%asl_playercount_hideplayers%` | Returns wether `playerCount -> hidePlayers` is enabled or not. | `false` |
| `%asl_playercount_hideplayershover%` | Returns wether `playerCount -> hidePlayersHover` is enabled or not. | `false` |
| `%asl_playercount_hover%` | Value of `playerCount -> hover`. | `(empty string)` |
| `%asl_playercount_maxplayers%` | Value of `playerCount -> maxPlayers -> amount` | `(empty string)` |
| `%asl_playercount_onlineplayers%` | Value of `playerCount -> onlinePlayers -> amount` | `(empty string)` |
| `%asl_playercount_text%` | Value of `playerCount -> text` | `(empty string)` |
| `%asl_playersmax%` | Returns the max players based on currently set maxPlayers or extraPlayers values. | `(empty string)` |
<small>^1^{ #papi-n1 } The default value is returned when the option in the chosen profile is either not set, or `null`.</small>
### Other Placeholders
Placeholders from PlaceholderAPI Expansions can be used in AdvancedServerList using the default `%identifier_value%` format.
PlaceholderAPI placeholders can be used both on the Server (Paper) and on the proxy (BungeeCord, Velocity) version of AdvancedServerList.
However, the Proxy version requires the usage of [PAPIProxyBridge] to function properly.
Placeholders can also not be used within the [`condition`](index.md#condition) option of a Server List Profile.
+7 -2
View File
@@ -80,6 +80,9 @@ plugins:
'migration/pre-v3_7_0-to-v3_7_0.md': 'migration/versions/pre-v3.7.0-to-v3.7.0.md'
'migration/v1_9_0-to-v1_10_0.md': 'migration/versions/v1.9.0-to-v1.10.0.md'
'migration/v1_5_3-to-v1_6_0.md': 'migration/versions/v1.5.3-to-v1.6.0.md'
#
# PlaceholderAPI page
'placeholderapi/index.md': 'profiles/placeholders.md#own-placeholders'
- pagenav-generator
markdown_extensions:
@@ -115,6 +118,7 @@ markdown_extensions:
- pymdownx.blocks.tab:
alternate_style: true
- pymdownx.blocks.details:
- pymdownx.caret:
hooks:
- docs/.hooks/badges.py
@@ -145,6 +149,8 @@ nav:
- v1.5.3 to v1.6.0: migration/versions/v1.5.3-to-v1.6.0.md
- API:
- api/index.md
- Adding Placeholders: api/adding-placeholders.md
- Listening for Events: api/listening-for-events.md
- Changelog: api/changelog.md
- Javadocs: api/javadocs.md
- Source Code: api/source.md
@@ -196,5 +202,4 @@ nav:
- api/reference/platform-velocity/ch.andre601.advancedserverlist.api.velocity/objects/velocityproxy.md
- Addons:
- addons/index.md
- BanPlugins: addons/banplugins.md
- PlaceholderAPI: placeholderapi/index.md
- BanPlugins: addons/banplugins.md
@@ -115,13 +115,15 @@ public class PAPIPlaceholders extends PlaceholderExpansion{
BukkitServer finalServer = new PaperServerImpl(plugin.getWorldCache().worlds(), online, max, host);
return switch(identifier.toLowerCase(Locale.ROOT)){
case "motd" -> getOption(entry.motd(), pl, player, finalServer, true);
case "favicon" -> getOption(entry.favicon(), pl, player, finalServer);
case "motd" -> getOption(entry.motd(), pl, player, finalServer, true);
case "playercount_extraplayers" -> extraPlayers == null ? "" : String.valueOf(extraPlayers);
case "playercount_hideplayers" -> String.valueOf(entry.hidePlayersEnabled().getOrDefault(false));
case "playercount_hideplayershover" -> String.valueOf(entry.hidePlayersHoverEnabled().getOrDefault(false));
case "playercount_hover" -> getOption(entry.players(), pl, player, finalServer, false);
case "playercount_maxplayers" -> maxPlayers == null ? "" : String.valueOf(maxPlayers);
case "playercount_onlineplayers" -> onlinePlayers == null ? "" : String.valueOf(onlinePlayers);
case "playercount_text" -> getOption(entry.playerCountText(), pl, player, finalServer);
case "playercount_extraplayers" -> extraPlayers == null ? "null" : String.valueOf(extraPlayers);
case "playercount_maxplayers" -> maxPlayers == null ? "null" : String.valueOf(maxPlayers);
case "playercount_onlineplayers" -> onlinePlayers == null ? "null" : String.valueOf(onlinePlayers);
case "server_playersmax" -> String.valueOf(max);
default -> null;
};
@@ -137,10 +139,16 @@ public class PAPIPlaceholders extends PlaceholderExpansion{
}
private String getOption(String str, Player pl, BukkitPlayer player, BukkitServer server){
if(str == null)
return "";
return getOption(Collections.singletonList(str), pl, player, server, false);
}
private String getOption(List<String> list, Player pl, BukkitPlayer player, BukkitServer server, boolean isMotd){
if(list.isEmpty())
return "";
return list.stream()
.map(line -> ComponentParser.text(line)
.modifyText(text -> StringReplacer.replace(text, player, server))
+1
View File
@@ -74,5 +74,6 @@
<module>velocity</module>
<module>version-uploader</module>
<module>addons/banplugins</module>
<module>addons/placeholderapi</module>
</modules>
</project>
@@ -30,14 +30,17 @@ import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.profiles.handlers.FaviconHandler;
import ch.andre601.advancedserverlist.velocity.commands.CmdAdvancedServerList;
import ch.andre601.advancedserverlist.velocity.listeners.JoinEvent;
import ch.andre601.advancedserverlist.velocity.listeners.PingEvent;
import ch.andre601.advancedserverlist.velocity.listeners.JoinListener;
import ch.andre601.advancedserverlist.velocity.listeners.PingListener;
import ch.andre601.advancedserverlist.velocity.listeners.PluginMessageListener;
import ch.andre601.advancedserverlist.velocity.logging.VelocityLogger;
import ch.andre601.advancedserverlist.velocity.objects.placeholders.VelocityPlayerPlaceholders;
import ch.andre601.advancedserverlist.velocity.objects.placeholders.VelocityProxyPlaceholders;
import ch.andre601.advancedserverlist.velocity.objects.placeholders.VelocityServerPlaceholders;
import com.alessiodp.libby.Library;
import com.alessiodp.libby.VelocityLibraryManager;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.google.inject.Inject;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.event.Subscribe;
@@ -46,6 +49,7 @@ import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerPing;
import com.velocitypowered.api.scheduler.ScheduledTask;
@@ -67,6 +71,7 @@ import java.util.concurrent.TimeUnit;
public class VelocityCore implements PluginCore<Favicon>{
public static final MinecraftChannelIdentifier ASL_IDENTIFIER = MinecraftChannelIdentifier.from("advancedserverlist:action");
private final Map<String, ServerPing> fetchedServers = new ConcurrentHashMap<>();
private final PluginLogger pluginLogger;
@@ -85,6 +90,7 @@ public class VelocityCore implements PluginCore<Favicon>{
@Inject
public VelocityCore(ProxyServer proxy, @DataDirectory Path path, Metrics.Factory metrics){
proxy.getChannelRegistrar().register(ASL_IDENTIFIER);
ComponentLogger logger = ComponentLogger.logger("AdvancedServerList");
this.pluginLogger = new VelocityLogger(this, logger);
this.logger = logger;
@@ -120,8 +126,9 @@ public class VelocityCore implements PluginCore<Favicon>{
@Override
public void loadEvents(){
new JoinEvent(this);
new PingEvent(this);
new JoinListener(this);
new PingListener(this);
new PluginMessageListener(this);
}
@Override
@@ -246,6 +253,11 @@ public class VelocityCore implements PluginCore<Favicon>{
return;
fetchedServers.put(server.getServerInfo().getName(), ping);
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("findPlugins");
server.sendPluginMessage(ASL_IDENTIFIER, out.toByteArray());
}));
}
}
@@ -33,11 +33,11 @@ import com.velocitypowered.api.proxy.Player;
import java.net.InetSocketAddress;
public class JoinEvent{
public class JoinListener{
private final VelocityCore plugin;
public JoinEvent(VelocityCore plugin){
public JoinListener(VelocityCore plugin){
this.plugin = plugin;
plugin.getProxy().getEventManager().register(plugin, this);
}
@@ -33,11 +33,11 @@ import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
public class PingEvent{
public class PingListener{
private final VelocityCore plugin;
public PingEvent(VelocityCore plugin){
public PingListener(VelocityCore plugin){
this.plugin = plugin;
plugin.getProxy().getEventManager().register(plugin, this);
}
@@ -0,0 +1,40 @@
package ch.andre601.advancedserverlist.velocity.listeners;
import ch.andre601.advancedserverlist.core.objects.PluginMessageUtil;
import ch.andre601.advancedserverlist.velocity.VelocityCore;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.proxy.ServerConnection;
public class PluginMessageListener{
public PluginMessageListener(VelocityCore plugin){
plugin.getProxy().getEventManager().register(plugin, this);
}
@Subscribe
public void onPluginMessage(PluginMessageEvent event){
if(!(event.getSource() instanceof ServerConnection))
return;
if(event.getIdentifier() != VelocityCore.ASL_IDENTIFIER)
return;
ByteArrayDataInput input = ByteStreams.newDataInput(event.getData());
String subChannel = input.readUTF();
switch(subChannel){
case "hasPlugin" -> {
String serverName = input.readUTF();
PluginMessageUtil.get().addServer(serverName);
}
case "parsed" -> {
String uuid = input.readUTF();
String parsed = input.readUTF();
PluginMessageUtil.get().queue(uuid, parsed, true);
}
}
}
}
@@ -29,17 +29,18 @@ import ch.andre601.advancedserverlist.api.events.GenericServerListEvent;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.core.compat.maintenance.MaintenanceUtil;
import ch.andre601.advancedserverlist.core.compat.papi.PAPIUtil;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.interfaces.events.GenericEventWrapper;
import ch.andre601.advancedserverlist.core.objects.CachedPlayer;
import ch.andre601.advancedserverlist.core.objects.PluginMessageUtil;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import ch.andre601.advancedserverlist.velocity.VelocityCore;
import ch.andre601.advancedserverlist.velocity.objects.impl.VelocityPlayerImpl;
import ch.andre601.advancedserverlist.velocity.objects.impl.VelocityProxyImpl;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerPing;
import com.velocitypowered.api.util.Favicon;
@@ -177,25 +178,25 @@ public class VelocityEventWrapper implements GenericEventWrapper<Favicon, Veloci
@Override
public String parsePAPIPlaceholders(String text, VelocityPlayerImpl player){
if(!plugin.getProxy().getPluginManager().isLoaded("papiproxybridge"))
return text;
if(!PAPIUtil.get().isCompatible())
return text;
String server = PAPIUtil.get().getServer();
if(server == null || server.isEmpty())
return text;
RegisteredServer registeredServer = plugin.getProxy().getServer(server).orElse(null);
if(registeredServer == null || registeredServer.getPlayersConnected().isEmpty())
return text;
Player carrier = PAPIUtil.get().getPlayer(registeredServer.getPlayersConnected());
if(carrier == null)
return text;
return PAPIUtil.get().parse(text, carrier.getUniqueId(), player.getUUID());
return PluginMessageUtil.get().getOrExecute(player.getUUID().toString(), text, (uuid, textValue) -> {
List<String> servers = PluginMessageUtil.get().getKnownServers();
if(servers.isEmpty())
return textValue;
RegisteredServer registeredServer = plugin.getProxy().getServer(servers.get(0)).orElse(null);
if(registeredServer == null)
return textValue;
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("parse");
out.writeUTF(uuid);
out.writeUTF(textValue);
registeredServer.sendPluginMessage(VelocityCore.ASL_IDENTIFIER, out.toByteArray());
PluginMessageUtil.get().queue(uuid, textValue, false);
return PluginMessageUtil.get().getOrDefault(uuid, textValue);
});
}
@Override