Compare commits

...
68 Commits
Author SHA1 Message Date
Andre601 2754bf13aa Allow support for vanished players 2024-03-10 14:01:10 +01:00
Andre601 9ff5fcdaa7 Unify Placeholder parsing system. 2024-03-07 22:01:18 +01:00
Andre601 0ba7ed6ece Merge pull request 'Update dependency com.viaversion:viaversion-api to v4.9.3' (#241) from renovate/com.viaversion-viaversion-api-4.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/241
2024-03-06 12:46:39 +00:00
Andre601 2d8c774401 Merge pull request 'Update dependency mkdocs-material to v9.5.13' (#242) from renovate/mkdocs-material-9.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/242
2024-03-06 12:46:23 +00:00
Andre601's Renovate Bot f68be63f64 Update dependency mkdocs-material to v9.5.13 2024-03-06 12:14:43 +00:00
Andre601's Renovate Bot 2695b393d8 Update dependency com.viaversion:viaversion-api to v4.9.3 2024-03-06 12:14:35 +00:00
Andre601 55821d2edf Merge pull request 'Update dependency ch.qos.logback:logback-classic to v1.5.3' (#240) from renovate/ch.qos.logback-logback-classic-1.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/240
2024-03-05 12:02:36 +00:00
Andre601's Renovate Bot b64e32503e Update dependency ch.qos.logback:logback-classic to v1.5.3 2024-03-05 12:01:13 +00:00
Andre601 c5ab9b118f Use code highlighting for expression examples 2024-03-05 02:11:01 +01:00
Andre601 6cc54349b5 Fix typo with fontawesome 2024-03-05 01:02:47 +00:00
Andre601 98d2de975e Add divider lines to optional dependencies 2024-03-05 00:59:59 +00:00
Andre601 6d1c118660 Remove unusued project.build.commit tag 2024-03-03 22:14:34 +01:00
Andre601 49e5b195ec Update way of reporting condition errors 2024-03-03 22:14:11 +01:00
Andre601 c92611e7f8 Merge pull request 'Update dependency ch.qos.logback:logback-classic to v1.5.2' (#238) from renovate/ch.qos.logback-logback-classic-1.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/238
2024-03-03 13:46:52 +00:00
Andre601's Renovate Bot 233414c45c Update dependency ch.qos.logback:logback-classic to v1.5.2 2024-03-03 12:01:19 +00:00
Andre601 c0629e10bc Add BanPlugins Addon to optional dependencies 2024-03-03 02:00:17 +00:00
Andre601 621eb7c489 Update API reference for ProfileEntry.Builder + changelog 2024-03-03 00:50:16 +01:00
Andre601 38e16f1d4b Bump version to 4.3.0 2024-03-03 00:14:42 +01:00
Andre601 2e61531079 Merge pull request 'Add LibertyBans' (#233) from feature/libertybans-addon into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/233
2024-03-02 23:12:05 +00:00
Andre601 5cf295d4c5 Merge branch 'master' into feature/libertybans-addon 2024-03-02 23:08:55 +00:00
Andre601 24d5865a57 Also add asl parent 2024-03-03 00:08:17 +01:00
Andre601 03c5e7d9d0 Add ExpressionParser to matchPackageNames 2024-03-03 00:08:17 +01:00
Andre601's Renovate Bot 7874fcf265 Update api.version to v3.2.1 2024-03-03 00:08:13 +01:00
Andre601 3e9070ebf9 Fix renovate.json 2024-03-03 00:06:12 +01:00
Andre601 478fa88a97 Also add asl parent 2024-03-02 12:10:33 +00:00
Andre601 346f94decc Add ExpressionParser to matchPackageNames 2024-03-02 12:09:06 +00:00
Andre601 f5e8a7e460 Merge pull request 'Update api.version to v3.2.1' (#237) from renovate/api.version into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/237
2024-03-02 12:06:58 +00:00
Andre601's Renovate Bot 3cb470a086 Update api.version to v3.2.1 2024-03-02 12:06:01 +00:00
Andre601 348ecce315 Fix renovate.json 2024-03-02 12:05:24 +00:00
Andre601 78463bca4f Merge branch 'master' into feature/libertybans-addon 2024-03-01 19:17:49 +00:00
Andre601 a6bde40f30 Update registry URL for asl API 2024-03-01 16:39:29 +00:00
Andre601 45fa7b5d69 Fix banExpiration placeholder using muteExpiration(player). 2024-03-01 16:18:34 +01:00
Andre601 1f52ff39d1 Update getting started guide 2024-02-29 16:06:42 +00:00
Andre601 bc66d925ff Merge pull request 'Update dependency mkdocs-material to v9.5.12' (#235) from renovate/mkdocs-material-9.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/235
2024-02-29 12:25:20 +00:00
Andre601 41f8f6b29d Merge branch 'master' into renovate/mkdocs-material-9.x 2024-02-29 12:25:07 +00:00
Andre601 e032b2cc7f Merge pull request 'Update dependency ch.qos.logback:logback-classic to v1.5.1' (#234) from renovate/ch.qos.logback-logback-classic-1.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/234
2024-02-29 12:24:51 +00:00
Andre601's Renovate Bot 7c6d4a3840 Update dependency mkdocs-material to v9.5.12 2024-02-29 12:01:25 +00:00
Andre601's Renovate Bot 2f2095237d Update dependency ch.qos.logback:logback-classic to v1.5.1 2024-02-29 12:01:20 +00:00
Andre601 2a20af1f9a Update Javadoc link 2024-02-29 11:45:05 +01:00
Andre601 c424c5abd5 Use custom admonition for files 2024-02-28 15:55:31 +01:00
Andre601 101fc593d2 Update files 2024-02-28 15:50:41 +01:00
Andre601 cb9e65105e Add LibertyBans placeholder docs 2024-02-26 23:17:42 +01:00
Andre601 9b95bb1222 docs/api/index.md aktualisiert 2024-02-26 19:41:17 +00:00
Andre601 2b01ed9725 Use Collections.max and Update PlatformInfo 2024-02-26 20:29:45 +01:00
Andre601 9b77a1274d Update Link for api/source redirect 2024-02-26 17:49:01 +01:00
Andre601 18d5cca185 Update Repository URL for API 2024-02-26 17:48:32 +01:00
Andre601 d5b604c1d0 Add LibertyBans 2024-02-26 17:18:00 +01:00
Andre601 e9b4ccbb93 Merge pull request 'Update dependency mkdocs-material to v9.5.11' (#232) from renovate/mkdocs-material-9.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/232
2024-02-24 12:03:07 +00:00
Andre601's Renovate Bot a14f8c961f Update dependency mkdocs-material to v9.5.11 2024-02-24 12:01:08 +00:00
Andre601 ba311f42c4 Use separated ExpressionParser system 2024-02-23 19:50:27 +01:00
Andre601 1b5379d54b Merge pull request 'Update dependency club.minnced:discord-webhooks to v0.8.4' (#231) from renovate/club.minnced-discord-webhooks-0.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/231
2024-02-23 12:02:14 +00:00
Andre601's Renovate Bot 03a1908ca6 Update dependency club.minnced:discord-webhooks to v0.8.4 2024-02-23 12:01:13 +00:00
Andre601 f9574d2f83 Add DISCORD_WEBHOOK_URL env variable to workflow 2024-02-22 13:42:41 +01:00
Andre601 7e45439dfe Merge pull request 'Make better local favicon handling' (#230) from feature/better-local-favicon-handling into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/230
2024-02-22 12:41:03 +00:00
Andre601 2a8b4ed640 Optimize Imports 2024-02-22 13:32:29 +01:00
Andre601 86c053e445 Remove unused createFavicon method in GenericEventWrapper 2024-02-22 13:29:39 +01:00
Andre601 7eba04bb9a Make better local favicon handling 2024-02-22 13:27:27 +01:00
Andre601 b4ac677f67 Merge pull request 'Update dependency org.apache.maven.plugins:maven-shade-plugin to v3.5.2' (#228) from renovate/org.apache.maven.plugins-maven-shade-plugin-3.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/228
2024-02-21 12:15:13 +00:00
Andre601 989d44cc5e Merge pull request 'Update dependency net.kyori:adventure-text-serializer-legacy to v4.16.0' (#229) from renovate/net.kyori-adventure-text-serializer-legacy-4.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/229
2024-02-21 12:15:00 +00:00
Andre601's Renovate Bot 9821875e7a Update dependency net.kyori:adventure-text-serializer-legacy to v4.16.0 2024-02-21 12:01:15 +00:00
Andre601's Renovate Bot 07e3b6702b Update dependency org.apache.maven.plugins:maven-shade-plugin to v3.5.2 2024-02-21 12:01:09 +00:00
Andre601 31889fbd9c Merge pull request 'Update dependency net.kyori:adventure-text-minimessage to v4.16.0' (#227) from renovate/net.kyori-adventure-text-minimessage-4.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/227
2024-02-20 12:12:40 +00:00
Andre601 87a089a0fa Merge pull request 'Update dependency net.kyori:adventure-api to v4.16.0' (#226) from renovate/net.kyori-adventure-api-4.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/226
2024-02-20 12:12:14 +00:00
Andre601 88b91e8859 Add AdvancedBan to special registry lookup 2024-02-20 12:09:55 +00:00
Andre601's Renovate Bot f8097e3c72 Update dependency net.kyori:adventure-text-minimessage to v4.16.0 2024-02-20 12:01:39 +00:00
Andre601's Renovate Bot e237c990d8 Update dependency net.kyori:adventure-api to v4.16.0 2024-02-20 12:01:33 +00:00
Andre601 21c0ba975c Merge pull request 'Update dependency mkdocs-material to v9.5.10' (#225) from renovate/mkdocs-material-9.x into master
Reviewed-on: https://codeberg.org/Andre601/AdvancedServerList/pulls/225
2024-02-19 12:02:37 +00:00
Andre601's Renovate Bot 642ce922c3 Update dependency mkdocs-material to v9.5.10 2024-02-19 12:01:15 +00:00
122 changed files with 1761 additions and 3785 deletions

No files matched your search

+2
View File
@@ -12,6 +12,8 @@ steps:
target: modrinth_api_token
- source: hangar_api_token
target: hangar_api_token
- source: discord_webhook_url
target: discord_webhook_url
commands:
# Create the jar files.
- mvn clean install
+16
View File
@@ -54,6 +54,10 @@
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>libertybans</id>
<url>https://mvn-repo.arim.space/affero-gpl3/</url>
</repository>
</repositories>
<dependencies>
@@ -78,6 +82,12 @@
<version>1.20-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.velocitypowered</groupId>
<artifactId>velocity-api</artifactId>
<version>3.3.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Plugin APIs -->
<dependency>
@@ -86,6 +96,12 @@
<version>v2.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>space.arim.libertybans</groupId>
<artifactId>bans-api</artifactId>
<version>1.1.0-RC1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.andre601.asl-api</groupId>
<artifactId>api</artifactId>
@@ -27,13 +27,15 @@ package ch.andre601.advancedserverlist.banplugins.bungeecord;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.banplugins.placeholders.AdvancedBanPlaceholders;
import ch.andre601.advancedserverlist.banplugins.placeholders.LibertyBansPlaceholders;
import java.util.HashMap;
import java.util.Map;
public enum BungeeCordBanPlugins{
ADVANCED_BAN("AdvancedBan", new AdvancedBanPlaceholders());
ADVANCED_BAN("AdvancedBan", new AdvancedBanPlaceholders()),
LIBERTY_BANS("LibertyBans", new LibertyBansPlaceholders());
private final String plugin;
private final PlaceholderProvider placeholderProvider;
@@ -25,8 +25,8 @@
package ch.andre601.advancedserverlist.banplugins.bungeecord;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.AdvancedServerListAPI;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import net.md_5.bungee.api.plugin.Plugin;
import java.util.Map;
@@ -27,13 +27,15 @@ package ch.andre601.advancedserverlist.banplugins.paper;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.banplugins.placeholders.AdvancedBanPlaceholders;
import ch.andre601.advancedserverlist.banplugins.placeholders.LibertyBansPlaceholders;
import java.util.HashMap;
import java.util.Map;
public enum PaperBanPlugins{
ADVANCED_BAN("AdvancedBan", new AdvancedBanPlaceholders());
ADVANCED_BAN("AdvancedBan", new AdvancedBanPlaceholders()),
LIBERTY_BANS("LibertyBans", new LibertyBansPlaceholders());
private final String plugin;
private final PlaceholderProvider placeholderProvider;
@@ -25,10 +25,10 @@
package ch.andre601.advancedserverlist.banplugins.placeholders;
import ch.andre601.advancedserverlist.banplugins.providers.AdvancedBanProvider;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.banplugins.providers.AdvancedBanProvider;
import java.util.Arrays;
@@ -44,7 +44,7 @@ public class AdvancedBanPlaceholders extends PlaceholderProvider{
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server){
String[] args = placeholder.split("\\s");
return switch(placeholder) {
return switch(args[0]) {
// Mute-related placeholders
case "isMuted" -> String.valueOf(provider.muted(player));
case "muteReason" -> provider.muteReason(player);
@@ -0,0 +1,76 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.banplugins.placeholders;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.banplugins.providers.LibertyBansProvider;
import java.util.Arrays;
public class LibertyBansPlaceholders extends PlaceholderProvider{
private final LibertyBansProvider provider = LibertyBansProvider.create();
public LibertyBansPlaceholders(){
super("libertybans");
}
@Override
public String parsePlaceholder(String placeholder, GenericPlayer player, GenericServer server){
String[] args = placeholder.split("\\.");
return switch(args[0]){
// Mute-related placeholders
case "isMuted" -> String.valueOf(provider.muted(player));
case "muteReason" -> provider.muteReason(player);
case "muteExpiration" -> {
if(args.length == 1)
yield provider.muteExpirationDate(player);
String pattern = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
yield provider.muteExpirationDate(player, pattern);
}
// Ban-related placeholders
case "isBanned" -> String.valueOf(provider.banned(player));
case "banReason" -> provider.banReason(player);
case "banExpiration" -> {
if(args.length == 1)
yield provider.banExpirationDate(player);
String pattern = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
yield provider.banExpirationDate(player, pattern);
}
// Unknown/Invalid placeholder
default -> null;
};
}
}
@@ -105,8 +105,7 @@ public class AdvancedBanProvider implements PunishmentProvider{
if(end < 0L)
return "never";
Date date = new Date(end);
return new SimpleDateFormat(pattern).format(date);
return this.returnDate(pattern, end);
}
@Override
@@ -119,8 +118,7 @@ public class AdvancedBanProvider implements PunishmentProvider{
if(end < 0L)
return "never";
Date date = new Date(end);
return new SimpleDateFormat(pattern).format(date);
return this.returnDate(pattern, end);
}
public String muteDuration(GenericPlayer player, boolean fromStart){
@@ -0,0 +1,136 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.banplugins.providers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import space.arim.libertybans.api.LibertyBans;
import space.arim.libertybans.api.PunishmentType;
import space.arim.libertybans.api.punish.Punishment;
import space.arim.libertybans.api.user.KnownAccount;
import space.arim.omnibus.Omnibus;
import space.arim.omnibus.OmnibusProvider;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
public class LibertyBansProvider implements PunishmentProvider{
private final LibertyBans libertyBans;
private LibertyBansProvider(LibertyBans libertyBans){
this.libertyBans = libertyBans;
}
public static LibertyBansProvider create(){
Omnibus omnibus = OmnibusProvider.getOmnibus();
LibertyBans libertyBans = omnibus.getRegistry().getProvider(LibertyBans.class).orElseThrow();
return new LibertyBansProvider(libertyBans);
}
@Override
public boolean muted(GenericPlayer player){
return punishment(player.getUUID(), PunishmentType.MUTE) != null;
}
@Override
public boolean banned(GenericPlayer player){
return punishment(player.getUUID(), PunishmentType.BAN) != null;
}
@Override
public String muteReason(GenericPlayer player){
Punishment mute = punishment(player.getUUID(), PunishmentType.MUTE);
if(mute == null)
return null;
return mute.getReason();
}
@Override
public String banReason(GenericPlayer player){
Punishment ban = punishment(player.getUUID(), PunishmentType.BAN);
if(ban == null)
return null;
return ban.getReason();
}
@Override
public String muteDuration(GenericPlayer player){
return null;
}
@Override
public String banDuration(GenericPlayer player){
return null;
}
@Override
public String muteExpirationDate(GenericPlayer player, String pattern){
Punishment mute = punishment(player.getUUID(), PunishmentType.MUTE);
if(mute == null)
return null;
if(mute.isPermanent())
return "never";
return this.returnDate(pattern, mute.getEndDate().toEpochMilli());
}
@Override
public String banExpirationDate(GenericPlayer player, String pattern){
Punishment ban = punishment(player.getUUID(), PunishmentType.BAN);
if(ban == null)
return null;
if(ban.isPermanent())
return "never";
return this.returnDate(pattern, ban.getEndDate().toEpochMilli());
}
private Punishment punishment(UUID uuid, PunishmentType type){
List<? extends KnownAccount> accounts = libertyBans.getAccountSupervisor()
.findAccountsMatching(uuid)
.join();
if(accounts.isEmpty())
return null;
KnownAccount sorted = Collections.max(accounts, Comparator.comparing(KnownAccount::recorded));
return libertyBans.getSelector()
.selectionByApplicabilityBuilder(sorted.uuid(), sorted.address())
.type(type)
.build()
.getFirstSpecificPunishment()
.toCompletableFuture()
.join()
.orElse(null);
}
}
@@ -27,7 +27,8 @@ package ch.andre601.advancedserverlist.banplugins.providers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import java.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import java.util.Date;
public interface PunishmentProvider{
@@ -55,4 +56,13 @@ public interface PunishmentProvider{
String banExpirationDate(GenericPlayer player, String pattern);
default String returnDate(String pattern, long end){
Date date = new Date(end);
try{
return new SimpleDateFormat(pattern).format(date);
}catch(IllegalArgumentException ex){
return new SimpleDateFormat("dd, MMM yyyy HH:mm:ss").format(date);
}
}
}
@@ -23,27 +23,34 @@
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions.expressions;
package ch.andre601.advancedserverlist.banplugins.velocity;
public interface ToBooleanExpression extends Expression{
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.banplugins.paper.PaperBanPlugins;
import ch.andre601.advancedserverlist.banplugins.placeholders.LibertyBansPlaceholders;
import java.util.HashMap;
import java.util.Map;
public enum VelocityBanPlugins{
boolean evaluate();
LIBERTY_BANS("libertybans", new LibertyBansPlaceholders());
static ToBooleanExpression literal(boolean value){
return new ConstantToBooleanExpression(value);
private final String plugin;
private final PlaceholderProvider placeholderProvider;
VelocityBanPlugins(String plugin, PlaceholderProvider placeholderProvider){
this.plugin = plugin;
this.placeholderProvider = placeholderProvider;
}
class ConstantToBooleanExpression implements ToBooleanExpression{
public static Map<String, PlaceholderProvider> getBanPlugins(){
Map<String, PlaceholderProvider> content = new HashMap<>();
private final boolean value;
public ConstantToBooleanExpression(boolean value){
this.value = value;
for(VelocityBanPlugins velocityBanPlugins : VelocityBanPlugins.values()){
content.put(velocityBanPlugins.plugin, velocityBanPlugins.placeholderProvider);
}
@Override
public boolean evaluate(){
return value;
}
return content;
}
}
@@ -0,0 +1,82 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.banplugins.velocity;
import ch.andre601.advancedserverlist.api.AdvancedServerListAPI;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import net.md_5.bungee.api.ProxyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class VelocityBanPluginsAddon{
private final Logger logger = LoggerFactory.getLogger("ASLBanPluginsAddon");
private final ProxyServer proxy;
@Inject
public VelocityBanPluginsAddon(ProxyServer proxy){
this.proxy = proxy;
}
@Subscribe
public void init(ProxyInitializeEvent event){
if(proxy.getPluginManager().getPlugin("advancedserverlist") == null){
logger.warn("AdvancedServerList is not enabled. This plugin requires it to function!");
return;
}
int loadedPlaceholders = loadPlaceholderProviders();
if(loadedPlaceholders == 0){
logger.warn("No compatible Ban plugin was found to register placeholders for.");
}else{
logger.info("Loaded {} Placeholder Set(s) for AdvancedServerList!", loadedPlaceholders);
}
}
private int loadPlaceholderProviders(){
int loaded = 0;
Map<String, PlaceholderProvider> banPlugins = VelocityBanPlugins.getBanPlugins();
AdvancedServerListAPI api = AdvancedServerListAPI.get();
for(Map.Entry<String, PlaceholderProvider> entry : banPlugins.entrySet()){
if(proxy.getPluginManager().getPlugin(entry.getKey()) != null){
logger.info("Registering placeholders for {}...", entry.getKey());
api.addPlaceholderProvider(entry.getValue());
logger.info("Placeholder successfully registered!");
loaded++;
}
}
return loaded;
}
}
@@ -6,5 +6,6 @@ description: 'AdvancedBan Add-on for AdvancedServerList to add placeholders to u
softDepends:
- AdvancedServerList
- AdvancedBan
- LibertyBans
main: 'ch.andre601.advancedserverlist.banplugins.bungeecord.BungeeCordBanPluginsAddon'
@@ -12,5 +12,8 @@ dependencies:
required: false
load: BEFORE
AdvancedBans:
required: false
load: BEFORE
LibertyBans:
required: false
load: BEFORE
@@ -0,0 +1,20 @@
{
"id": "aslbanpluginsaddon",
"name": "ASLBanPluginsAddon",
"version": "${plugin.version}",
"description": "${plugin.description}",
"authors": [
"Andre_601"
],
"dependencies": [
{
"id": "advancedserverlist",
"optional": true
},
{
"id": "libertybans",
"optional": true
}
],
"main": "ch.andre601.advancedserverlist.banplugins.velocity.VelocityBanPluginsAddon"
}
+19 -3
View File
@@ -64,6 +64,8 @@
<version>${api.version}</version>
<scope>compile</scope>
</dependency>
<!-- BungeeCord API -->
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
@@ -78,16 +80,18 @@
<type>javadoc</type>
<scope>provided</scope>
</dependency>
<!-- Adventure Library. Needs to be shaded in -->
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.15.0</version>
<version>4.16.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-minimessage</artifactId>
<version>4.15.0</version>
<version>4.16.0</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -96,18 +100,30 @@
<version>4.3.2</version>
<scope>compile</scope>
</dependency>
<!-- Metrics -->
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bungeecord</artifactId>
<version>3.0.2</version>
<scope>compile</scope>
</dependency>
<!-- Configurate -->
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>configurate-yaml</artifactId>
<version>4.1.2</version>
<scope>compile</scope>
</dependency>
<!-- Plugins -->
<dependency>
<groupId>com.github.LeonMangler</groupId>
<artifactId>PremiumVanishAPI</artifactId>
<version>2.9.0-4</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
@@ -127,7 +143,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.5.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
@@ -29,18 +29,24 @@ 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.logging.BungeeLogger;
import ch.andre601.advancedserverlist.bungeecord.objects.BungeePlayerPlaceholders;
import ch.andre601.advancedserverlist.bungeecord.objects.BungeeServerPlaceholders;
import ch.andre601.advancedserverlist.bungeecord.objects.placeholders.BungeePlayerPlaceholders;
import ch.andre601.advancedserverlist.bungeecord.objects.placeholders.BungeeServerPlaceholders;
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.profiles.favicon.FaviconHandler;
import de.myzelyam.api.vanish.BungeeVanishAPI;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Plugin;
import org.bstats.bungeecord.Metrics;
import org.bstats.charts.SimplePie;
import java.awt.image.BufferedImage;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
@@ -50,7 +56,7 @@ public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
@Override
public void onEnable(){
this.core = AdvancedServerList.init(this, BungeePlayerPlaceholders.init(), BungeeServerPlaceholders.init());
this.core = AdvancedServerList.init(this, BungeePlayerPlaceholders.init(), BungeeServerPlaceholders.init(this));
}
@Override
@@ -77,12 +83,17 @@ public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
}
@Override
public void loadFaviconHandler(AdvancedServerList<Favicon> core){
faviconHandler = new FaviconHandler<>(core);
}
@Override
public void clearFaviconCache(){
if(faviconHandler == null)
return;
faviconHandler.clearCache();
faviconHandler.cleanCache();
}
@Override
@@ -122,4 +133,20 @@ public class BungeeCordCore extends Plugin implements PluginCore<Favicon>{
public String getLoader(){
return "bungeecord";
}
@Override
public Favicon createFavicon(BufferedImage image) throws IllegalArgumentException{
return Favicon.create(image);
}
public int getOnlinePlayers(ServerInfo server){
List<ProxiedPlayer> players = new ArrayList<>(server == null ? getProxy().getPlayers() : server.getPlayers());
// Exclude players when PremiumVanish is enabled and player is hidden.
if(getProxy().getPluginManager().getPlugin("PremiumVanish") != null){
players.removeIf(BungeeVanishAPI::isInvisible);
}
return players.size();
}
}
@@ -25,12 +25,12 @@
package ch.andre601.advancedserverlist.bungeecord.listeners;
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.bungeecord.BungeeCordCore;
import ch.andre601.advancedserverlist.bungeecord.objects.BungeePlayerImpl;
import ch.andre601.advancedserverlist.api.events.GenericServerListEvent;
import ch.andre601.advancedserverlist.bungeecord.objects.BungeeProxyImpl;
import ch.andre601.advancedserverlist.bungeecord.objects.impl.BungeePlayerImpl;
import ch.andre601.advancedserverlist.bungeecord.objects.impl.BungeeProxyImpl;
import ch.andre601.advancedserverlist.core.events.PingEventHandler;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.interfaces.events.GenericEventWrapper;
@@ -46,7 +46,6 @@ 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.awt.image.BufferedImage;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
@@ -148,7 +147,7 @@ public class BungeeEventWrapper implements GenericEventWrapper<Favicon, BungeePl
@Override
public int getOnlinePlayers(){
return ping.getPlayers().getOnline();
return plugin.getOnlinePlayers(null);
}
@Override
@@ -205,9 +204,4 @@ public class BungeeEventWrapper implements GenericEventWrapper<Favicon, BungeePl
return new BungeeProxyImpl(servers, playersOnline, playersMax, host);
}
@Override
public Favicon createFavicon(BufferedImage image) throws IllegalArgumentException{
return Favicon.create(image);
}
}
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2022-2023 Andre_601
* Copyright (c) 2022-2024 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
@@ -23,7 +23,7 @@
*
*/
package ch.andre601.advancedserverlist.bungeecord.objects;
package ch.andre601.advancedserverlist.bungeecord.objects.impl;
import ch.andre601.advancedserverlist.core.objects.CachedPlayer;
import ch.andre601.advancedserverlist.core.profiles.players.GenericPlayerImpl;
@@ -31,8 +31,8 @@ import ch.andre601.advancedserverlist.core.profiles.players.GenericPlayerImpl;
public class BungeePlayerImpl extends GenericPlayerImpl{
public BungeePlayerImpl(CachedPlayer player, int protocol){
this.name = player.getName();
this.name = player.name();
this.protocol = protocol;
this.uuid = player.getUuid();
this.uuid = player.uuid();
}
}
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2022-2023 Andre_601
* Copyright (c) 2022-2024 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
@@ -23,7 +23,7 @@
*
*/
package ch.andre601.advancedserverlist.bungeecord.objects;
package ch.andre601.advancedserverlist.bungeecord.objects.impl;
import ch.andre601.advancedserverlist.api.bungeecord.objects.BungeeProxy;
import net.md_5.bungee.api.config.ServerInfo;
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2022-2023 Andre_601
* Copyright (c) 2022-2024 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
@@ -23,7 +23,7 @@
*
*/
package ch.andre601.advancedserverlist.bungeecord.objects;
package ch.andre601.advancedserverlist.bungeecord.objects.placeholders;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2022-2023 Andre_601
* Copyright (c) 2022-2024 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
@@ -23,24 +23,28 @@
*
*/
package ch.andre601.advancedserverlist.bungeecord.objects;
package ch.andre601.advancedserverlist.bungeecord.objects.placeholders;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.bungeecord.objects.BungeeProxy;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.bungeecord.BungeeCordCore;
import net.md_5.bungee.api.config.ServerInfo;
import java.net.InetSocketAddress;
public class BungeeServerPlaceholders extends PlaceholderProvider{
private BungeeServerPlaceholders(){
private final BungeeCordCore plugin;
private BungeeServerPlaceholders(BungeeCordCore plugin){
super("server");
this.plugin = plugin;
}
public static BungeeServerPlaceholders init(){
return new BungeeServerPlaceholders();
public static BungeeServerPlaceholders init(BungeeCordCore plugin){
return new BungeeServerPlaceholders(plugin);
}
@Override
@@ -64,7 +68,7 @@ public class BungeeServerPlaceholders extends PlaceholderProvider{
if(info == null)
continue;
players += info.getPlayers().size();
players += plugin.getOnlinePlayers(info);
}
yield String.valueOf(players);
+21 -5
View File
@@ -41,7 +41,7 @@
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<plugin.config.version>3</plugin.config.version>
<plugin.config.version>4</plugin.config.version>
</properties>
<repositories>
@@ -57,6 +57,10 @@
<id>sonatype</id>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
<repository>
<id>codeberg</id>
<url>https://codeberg.org/api/packages/Andre601/maven/</url>
</repository>
</repositories>
<dependencies>
@@ -66,6 +70,12 @@
<version>${api.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.andre601</groupId>
<artifactId>expressionparser</artifactId>
<version>1.3.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>configurate-yaml</artifactId>
@@ -77,21 +87,23 @@
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.15.0</version>
<version>4.16.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-minimessage</artifactId>
<version>4.15.0</version>
<version>4.16.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-serializer-legacy</artifactId>
<version>4.15.0</version>
<version>4.16.0</version>
<scope>provided</scope>
</dependency>
<!-- Misc -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
@@ -151,7 +163,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.5.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
@@ -168,6 +180,10 @@
<pattern>com.unascribed</pattern>
<shadedPattern>ch.andre601.advancedserverlist.core.depends.flexver</shadedPattern>
</relocation>
<relocation>
<pattern>ch.andre601.expressionparser</pattern>
<shadedPattern>ch.andre601.advancedserverlist.core.depends.expressionparser</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
@@ -31,12 +31,11 @@ import ch.andre601.advancedserverlist.core.check.UpdateChecker;
import ch.andre601.advancedserverlist.core.commands.CommandHandler;
import ch.andre601.advancedserverlist.core.file.FileHandler;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionEngine;
import ch.andre601.advancedserverlist.core.profiles.conditions.ProfileConditionParser;
import ch.andre601.advancedserverlist.core.profiles.players.PlayerHandler;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
@@ -47,8 +46,8 @@ public class AdvancedServerList<F>{
private final FileHandler fileHandler;
private final CommandHandler commandHandler;
private final PlayerHandler playerHandler;
private final AdvancedServerListAPI api = AdvancedServerListAPI.get();
private final ExpressionEngine expressionEngine = new ExpressionEngine();
private static final AdvancedServerListAPI api = AdvancedServerListAPI.get();
private final ProfileConditionParser parser = ProfileConditionParser.create();
private UpdateChecker updateChecker;
@@ -60,7 +59,7 @@ public class AdvancedServerList<F>{
this.commandHandler = new CommandHandler(this);
this.playerHandler = new PlayerHandler(this);
placeholders.forEach(this.api::addPlaceholderProvider);
placeholders.forEach(AdvancedServerList.getApi()::addPlaceholderProvider);
load();
}
@@ -89,12 +88,12 @@ public class AdvancedServerList<F>{
return version;
}
public AdvancedServerListAPI getApi(){
public static AdvancedServerListAPI getApi(){
return api;
}
public ExpressionEngine getExpressionEngine(){
return expressionEngine;
public ProfileConditionParser getParser(){
return parser;
}
public void disable(){
@@ -148,9 +147,7 @@ public class AdvancedServerList<F>{
return;
}
Path folder = getPlugin().getFolderPath().resolve("favicons");
if(!folder.toFile().exists() && folder.toFile().mkdirs())
getPlugin().getPluginLogger().info("Successfully created favicons folder.");
getPlugin().loadFaviconHandler(this);
getPlugin().getPluginLogger().info("Loading Commands...");
plugin.loadCommands();
@@ -27,7 +27,10 @@ package ch.andre601.advancedserverlist.core.compat.papi;
import net.william278.papiproxybridge.api.PlaceholderAPI;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
@@ -30,10 +30,10 @@ import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
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.PluginLogger;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.interfaces.events.GenericEventWrapper;
import ch.andre601.advancedserverlist.core.compat.papi.PAPIUtil;
import ch.andre601.advancedserverlist.core.parsing.ComponentParser;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.core.profiles.profile.ProfileManager;
@@ -148,26 +148,18 @@ public class PingEventHandler{
if(ProfileManager.checkOption(entry.favicon())){
logger.debug(PingEventHandler.class, "Favicon set. Resolving '%s'...", entry.favicon());
String favicon = StringReplacer.replace(entry.favicon(), player, server);
String faviconString = StringReplacer.replace(entry.favicon(), player, server);
F fav = plugin.getFaviconHandler().getFavicon(favicon, image -> {
try{
logger.debug(PingEventHandler.class, "Converting BufferedImage to Server or Proxy Favicon instance...");
return event.createFavicon(image);
}catch(Exception ex){
plugin.getPluginLogger().warn("Encountered an Exception while creating Favicon!", ex);
return null;
}
});
F favicon = plugin.getFaviconHandler().getFavicon(faviconString);
if(fav == null){
if(favicon == null){
logger.debugWarn(PingEventHandler.class, "Favicon was invalid or not yet resolved! Using default favicon of Server/Proxy...");
event.setDefaultFavicon();
}else{
logger.debug(PingEventHandler.class, "Applying favicon...");
event.setFavicon(fav);
event.setFavicon(favicon);
}
}
@@ -46,18 +46,29 @@ public class ConfigMigrator{
public static ConfigurationTransformation.Versioned create(){
return ConfigurationTransformation.versionedBuilder()
.versionKey("configVersion")
.addVersion(LATEST, twoToThree())
.addVersion(LATEST, threeToFour())
.addVersion(3, twoToThree())
.addVersion(2, oneToTwo())
.build();
}
public static ConfigurationTransformation threeToFour(){
return ConfigurationTransformation.builder()
.addAction(NodePath.path(), (path, value) -> {
value.node("faviconCacheTime").set(1);
return null;
})
.build();
}
public static ConfigurationTransformation twoToThree(){
return ConfigurationTransformation.builder()
.addAction(NodePath.path(), ((path, value) -> {
.addAction(NodePath.path(), (path, value) -> {
value.node("debug").set(false);
return null;
}))
})
.build();
}
@@ -25,10 +25,10 @@
package ch.andre601.advancedserverlist.core.file;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.core.profiles.profile.ProfileSerializer;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.ConfigurationNode;
@@ -191,6 +191,11 @@ public class FileHandler{
return node.node(path).getBoolean();
}
public long getLong(long def, long limit, Object... path){
long value = node.node(path).getLong(def);
return Math.max(value, limit);
}
public boolean isOldConfig(){
return node.node("configVersion").virtual() || node.node("configVersion").getInt(0) < ConfigMigrator.LATEST;
}
@@ -29,6 +29,7 @@ import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.favicon.FaviconHandler;
import java.awt.image.BufferedImage;
import java.nio.file.Path;
public interface PluginCore<F>{
@@ -39,6 +40,8 @@ public interface PluginCore<F>{
void loadMetrics();
void loadFaviconHandler(AdvancedServerList<F> core);
void clearFaviconCache();
AdvancedServerList<F> getCore();
@@ -55,7 +58,12 @@ public interface PluginCore<F>{
String getLoader();
F createFavicon(BufferedImage image) throws Exception;
default boolean isDebugEnabled(){
if(getCore() == null)
return false;
return getCore().getFileHandler().getBoolean("debug");
}
}
@@ -25,15 +25,14 @@
package ch.andre601.advancedserverlist.core.interfaces.events;
import ch.andre601.advancedserverlist.api.events.GenericServerListEvent;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.api.events.GenericServerListEvent;
import ch.andre601.advancedserverlist.core.interfaces.core.PluginCore;
import ch.andre601.advancedserverlist.core.objects.CachedPlayer;
import net.kyori.adventure.text.Component;
import java.awt.image.BufferedImage;
import java.net.InetSocketAddress;
import java.util.List;
@@ -79,8 +78,6 @@ public interface GenericEventWrapper<F, P extends GenericPlayer>{
GenericServer createGenericServer(int playersOnline, int playersMax, String host);
F createFavicon(BufferedImage image) throws Exception;
default String resolveHost(InetSocketAddress address){
return address == null ? null : address.getHostString();
}
@@ -27,28 +27,4 @@ package ch.andre601.advancedserverlist.core.objects;
import java.util.UUID;
@SuppressWarnings("FieldMayBeFinal")
public class CachedPlayer{
private String ip;
private String name;
private UUID uuid;
public CachedPlayer(String ip, String name, UUID uuid){
this.ip = ip;
this.name = name;
this.uuid = uuid;
}
public String getIp(){
return ip;
}
public String getName(){
return name;
}
public UUID getUuid(){
return uuid;
}
}
public record CachedPlayer(String ip, String name, UUID uuid){}
@@ -29,9 +29,9 @@ import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionEngine;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.ProfileConditionParser;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.templates.ExpressionTemplate;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
@@ -39,24 +39,36 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public record ServerListProfile(int priority, String condition, ProfileEntry defaultProfile, List<ProfileEntry> profiles){
public record ServerListProfile(int priority, String condition, ProfileEntry defaultProfile, List<ProfileEntry> profiles, String file){
private static final Random random = new Random();
public boolean evalConditions(ExpressionEngine expressionEngine, PluginLogger logger, GenericPlayer player, GenericServer server){
public boolean evalConditions(ProfileConditionParser parser, PluginLogger logger, GenericPlayer player, GenericServer server){
if(condition == null || condition.isEmpty())
return true;
ExpressionsWarnHelper warnHelper = new ExpressionsWarnHelper(condition);
ExpressionTemplate template = expressionEngine.compile(condition, player, server, warnHelper);
ParseWarnCollector collector = new ParseWarnCollector(condition);
ExpressionTemplate template = parser.compile(condition, player, server, collector);
if(warnHelper.hasWarnings()){
warnHelper.printWarnings(logger);
if(collector.hasWarnings()){
logger.warn("Encountered %d Error(s) while parsing condition for file '%s':", collector.getWarnings().size(), file);
if(template == null)
return false;
for(ParseWarnCollector.Context context : collector.getWarnings()){
if(context.position() <= -1){
logger.warn(" - %s", condition);
logger.warn(" -> %s", context.message());
}else{
logger.warn(" - At position %d:", context.position());
logger.warn(" %s", condition);
logger.warn(" ".repeat(context.position() + 5) + "^");
logger.warn(" -> %s", context.message());
}
}
}
return template.instantiateWithBooleanResult().evaluate();
if(template == null)
return false;
return template.returnBooleanExpression().evaluate();
}
public ProfileEntry getRandomProfile(){
@@ -151,7 +163,7 @@ public record ServerListProfile(int priority, String condition, ProfileEntry def
}
public ServerListProfile build(){
return new ServerListProfile(this.priority, this.condition, this.defaultProfile, this.profiles);
return new ServerListProfile(this.priority, this.condition, this.defaultProfile, this.profiles, this.fileName);
}
}
}
@@ -1,107 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.AbstractUnaryToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.AbstractUnaryToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.AbstractUnaryToStringExpression;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Conversions{
private final static NumberFormat NUMBER_FORMAT;
static {
NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.ROOT);
NUMBER_FORMAT.setGroupingUsed(false);
}
public static ToBooleanExpression toBoolean(ToDoubleExpression expression){
return new AbstractUnaryToBooleanExpression<>(expression) {
@Override
public boolean evaluate(){
return delegate.evaluate() != 0;
}
};
}
public static ToBooleanExpression toBoolean(ToStringExpression expression){
return new AbstractUnaryToBooleanExpression<>(expression) {
@Override
public boolean evaluate(){
return Boolean.parseBoolean(delegate.evaluate());
}
};
}
public static ToDoubleExpression toDouble(ToBooleanExpression expression){
return new AbstractUnaryToDoubleExpression<>(expression) {
@Override
public double evaluate(){
return delegate.evaluate() ? 1 : 0;
}
};
}
public static ToDoubleExpression toDouble(ToStringExpression expression){
return new AbstractUnaryToDoubleExpression<>(expression) {
@Override
public double evaluate(){
String result = delegate.evaluate();
try{
return NUMBER_FORMAT.parse(result).doubleValue();
}catch(ParseException | NumberFormatException ex){
return 0;
}
}
};
}
public static ToStringExpression toString(ToBooleanExpression expression){
return new AbstractUnaryToStringExpression<>(expression) {
@Override
public String evaluate(){
return Boolean.toString(delegate.evaluate());
}
};
}
public static ToStringExpression toString(ToDoubleExpression expression){
return new AbstractUnaryToStringExpression<>(expression) {
@Override
public String evaluate(){
double result = delegate.evaluate();
return result == (int)result ? Integer.toString((int)result) : Double.toString(result);
}
};
}
}
@@ -1,226 +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.profiles.conditions;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
public class Expression{
private final ExpressionResult result;
private final String left;
private final Operator operator;
private final String right;
private Expression(ExpressionResult result, String left, Operator operator, String right){
this.result = result;
this.left = left;
this.operator = operator;
this.right = right;
}
public static Expression createInvalid(ExpressionResult result){
return new Expression(result, null, Operator.UNKNOWN, null);
}
public static Expression resolve(String expression){
Operator operator = Operator.UNKNOWN;
if(expression == null || expression.isEmpty()){
return Expression.createInvalid(ExpressionResult.INVALID_NO_EXPRESSION);
}
char[] chars = expression.toCharArray();
StringBuilder leftBuilder = new StringBuilder();
StringBuilder rightBuilder = new StringBuilder();
boolean foundOperator = false;
for(int i = 0; i < chars.length; i++){
char c = chars[i];
char next = (i == (chars.length - 1)) ? '\0' : chars[i + 1];
Operator tmp = Operator.getOperand(c, next);
if(tmp != Operator.UNKNOWN && !foundOperator){
operator = tmp;
foundOperator = true;
if(tmp.hasSecond())
i++; // Skip next character if operator has 2
continue;
}
if(foundOperator){
rightBuilder.append(c);
}else{
leftBuilder.append(c);
}
}
if(leftBuilder.isEmpty() || rightBuilder.isEmpty()){
return Expression.createInvalid(ExpressionResult.INVALID_EMPTY_PARTS);
}
return new Expression(ExpressionResult.VALID, leftBuilder.toString().trim(), operator, rightBuilder.toString().trim());
}
public boolean evaluate(GenericPlayer player, GenericServer server){
String newLeft = StringReplacer.replace(left, player, server);
String newRight = StringReplacer.replace(right, player, server);
return operator.evaluate(newLeft, newRight);
}
public ExpressionResult getResult(){
return result;
}
public enum Operator{
LESS('<', '\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);
}
},
EQUALS_IGNORE_CASE('~', '='){
@Override
public boolean evaluate(String left, String right){
return left.equalsIgnoreCase(right);
}
},
NOT_EQUAL('!', '='){
@Override
public boolean evaluate(String left, String right){
return !left.equals(right);
}
},
NOT_EQUAL_IGNORE_CASE('!', '~'){
@Override
public boolean evaluate(String left, String right){
return !left.equalsIgnoreCase(right);
}
},
GREATER('>', '\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 != '=' && 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(null),
INVALID_NO_EXPRESSION("Received empty condition which isn't allowed!"),
INVALID_EMPTY_PARTS ("Received condition with either left or right part being empty.");
private final String message;
ExpressionResult(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
}
@@ -0,0 +1,78 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader.PlaceholderTokenReader;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader.PlaceholderValueReader;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.tokens.CustomExpressionTokenizer;
import ch.andre601.expressionparser.ExpressionParserEngine;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.operator.Operator;
import ch.andre601.expressionparser.parsers.ExpressionTemplateParser;
import ch.andre601.expressionparser.parsers.ValueReader;
import ch.andre601.expressionparser.templates.ExpressionTemplate;
import ch.andre601.expressionparser.tokens.Token;
import ch.andre601.expressionparser.tokens.readers.TokenReader;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.List;
public class ProfileConditionParser implements ExpressionParserEngine{
private final CustomExpressionTokenizer tokenizer;
private final ExpressionTemplateParser parser;
private ProfileConditionParser(List<TokenReader> tokenReaders, ImmutableMap<Token, Operator> operators, ImmutableList<ValueReader> valueReaders){
this.tokenizer = new CustomExpressionTokenizer(tokenReaders);
this.parser = new ExpressionTemplateParser(operators, valueReaders);
}
public static ProfileConditionParser create(){
return new ProfileConditionParserBuilder().addDefaults()
.addTokenReader(new PlaceholderTokenReader(-20))
.addValueReader(new PlaceholderValueReader())
.build();
}
public ExpressionTemplate compile(String text, GenericPlayer player, GenericServer server, ParseWarnCollector collector){
return parser.parse(tokenizer.parse(text, player, server, collector), collector);
}
@Override
public ExpressionTemplate compile(String s, ParseWarnCollector parseWarnCollector){
return null;
}
private static class ProfileConditionParserBuilder extends ExpressionParserEngine.Builder<ProfileConditionParser>{
@Override
public ProfileConditionParser build(){
return new ProfileConditionParser(this.getTokenReaders(), ImmutableMap.copyOf(this.getOperators()), ImmutableList.copyOf(this.getValueReaders()));
}
}
}
@@ -1,28 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
public interface Expression{}
@@ -1,177 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.conditions.ExpressionTokenizer;
import ch.andre601.advancedserverlist.core.profiles.conditions.operators.ListOperator;
import ch.andre601.advancedserverlist.core.profiles.conditions.operators.Operator;
import ch.andre601.advancedserverlist.core.profiles.conditions.parsers.*;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplates;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.BooleanToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.DefaultTokens;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.readers.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExpressionEngine{
private final ExpressionTokenizer tokenizer;
private final ExpressionTemplateParser templateParser;
public ExpressionEngine(){
Options options = new Options.Builder()
.withDefaultTokenReaders()
.withDefaultOperators()
.withDefaultValueReaders()
.build();
this.tokenizer = new ExpressionTokenizer(options.tokenReaders);
this.templateParser = new ExpressionTemplateParser(options.operators, options.valueReaders);
}
public ExpressionTemplate compile(String expression, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
return templateParser.parse(tokenizer.parse(expression, player, server, warnHelper), warnHelper);
}
public static class Options{
private final List<TokenReader> tokenReaders;
private final ImmutableMap<Token, Operator> operators;
private final ImmutableList<ValueReader> valueReaders;
private Options(List<TokenReader> tokenReaders, ImmutableMap<Token, Operator> operators, ImmutableList<ValueReader> valueReaders){
this.tokenReaders = tokenReaders;
this.operators = operators;
this.valueReaders = valueReaders;
}
public static class Builder{
private final List<TokenReader> tokenReaders = new ArrayList<>();
private final Map<Token, Operator> operators = new HashMap<>();
private final List<ValueReader> valueReaders = new ArrayList<>();
public Builder(){}
public Builder withDefaultTokenReaders(){
return this
.tokenReader(new PatternTokenReader(BooleanToken.FALSE, "false"))
.tokenReader(new PatternTokenReader(BooleanToken.TRUE, "true"))
.tokenReader(new PatternTokenReader(DefaultTokens.AND, "and"))
.tokenReader(new PatternTokenReader(DefaultTokens.AND, "&&"))
.tokenReader(new PatternTokenReader(DefaultTokens.OR, "or"))
.tokenReader(new PatternTokenReader(DefaultTokens.OR, "||"))
.tokenReader(new PatternTokenReader(DefaultTokens.EQUAL, "=="))
.tokenReader(new PatternTokenReader(DefaultTokens.EQUAL_IGNORE_CASE, "=~"))
.tokenReader(new PatternTokenReader(DefaultTokens.EQUAL, "="))
.tokenReader(new PatternTokenReader(DefaultTokens.EQUAL_IGNORE_CASE, "~"))
.tokenReader(new PatternTokenReader(DefaultTokens.NOT_EQUAL, "!="))
.tokenReader(new PatternTokenReader(DefaultTokens.NOT_EQUAL_IGNORE_CASE, "!~"))
.tokenReader(new PatternTokenReader(DefaultTokens.STARTS_WITH, "|-"))
.tokenReader(new PatternTokenReader(DefaultTokens.ENDS_WITH, "-|"))
.tokenReader(new PatternTokenReader(DefaultTokens.CONTAINS, "<_"))
.tokenReader(new PatternTokenReader(DefaultTokens.GREATER_OR_EQUAL_THAN, ">="))
.tokenReader(new PatternTokenReader(DefaultTokens.LESSER_OR_EQUAL_THAN, "<="))
.tokenReader(new PatternTokenReader(DefaultTokens.OPENING_PARENTHESIS, "("))
.tokenReader(new PatternTokenReader(DefaultTokens.CLOSING_PARENTHESIS, ")"))
.tokenReader(new PatternTokenReader(DefaultTokens.NEGATION, "!"))
.tokenReader(new PatternTokenReader(DefaultTokens.GREATER_THAN, ">"))
.tokenReader(new PatternTokenReader(DefaultTokens.LESSER_THAN, "<"))
.tokenReader(new PatternTokenReader(DefaultTokens.CONCAT_STRING, "."))
.tokenReader(new PatternTokenReader(DefaultTokens.ADD, "+"))
.tokenReader(new PatternTokenReader(DefaultTokens.SUB, "-"))
.tokenReader(new PatternTokenReader(DefaultTokens.MULT, "*"))
.tokenReader(new PatternTokenReader(DefaultTokens.DIV, "/"))
.tokenReader(new QuotedLiteralTokenReader(-10, '\"'))
.tokenReader(new QuotedLiteralTokenReader(-10, '\''))
.tokenReader(new PlaceholderTokenReader(-20))
.tokenReader(new NumberTokenReader(-50))
.tokenReader(new NonQuotedLiteralTokenReader(-100));
}
public Builder withDefaultOperators(){
return this
.operator(DefaultTokens.AND, ListOperator.of(100, ExpressionTemplates::and))
.operator(DefaultTokens.OR, ListOperator.of(50, ExpressionTemplates::or))
.operator(DefaultTokens.EQUAL, Operator.of(25, ExpressionTemplates::equal))
.operator(DefaultTokens.NOT_EQUAL, Operator.of(25, ExpressionTemplates::notEqual))
.operator(DefaultTokens.EQUAL_IGNORE_CASE, Operator.of(25, ExpressionTemplates::equalIgnoreCase))
.operator(DefaultTokens.NOT_EQUAL_IGNORE_CASE, Operator.of(25, ExpressionTemplates::notEqualIgnoreCase))
.operator(DefaultTokens.STARTS_WITH, Operator.of(25, ExpressionTemplates::startsWith))
.operator(DefaultTokens.ENDS_WITH, Operator.of(25, ExpressionTemplates::endsWith))
.operator(DefaultTokens.CONTAINS, Operator.of(25, ExpressionTemplates::contains))
.operator(DefaultTokens.GREATER_THAN, Operator.of(25, ExpressionTemplates::greater))
.operator(DefaultTokens.GREATER_OR_EQUAL_THAN, Operator.of(25, ExpressionTemplates::greaterOrEqual))
.operator(DefaultTokens.LESSER_THAN, Operator.of(25, ExpressionTemplates::less))
.operator(DefaultTokens.LESSER_OR_EQUAL_THAN, Operator.of(25, ExpressionTemplates::lessOrEqual))
.operator(DefaultTokens.CONCAT_STRING, ListOperator.of(10, ExpressionTemplates::concat))
.operator(DefaultTokens.ADD, ListOperator.of(4, ExpressionTemplates::sum))
.operator(DefaultTokens.SUB, Operator.of(3, ExpressionTemplates::sub))
.operator(DefaultTokens.MULT, ListOperator.of(2, ExpressionTemplates::product))
.operator(DefaultTokens.DIV, Operator.of(1, ExpressionTemplates::div));
}
public Builder withDefaultValueReaders(){
return this
.valueReader(new BooleanConstantReader())
.valueReader(new NumberConstantReader())
.valueReader(new StringConstantReader())
.valueReader(new NegatedExpressionReader(DefaultTokens.NEGATION))
.valueReader(new ParenthesisedExpressionReader(DefaultTokens.OPENING_PARENTHESIS, DefaultTokens.CLOSING_PARENTHESIS))
.valueReader(new PlaceholderReader())
.valueReader(new NegatedNumberReader(DefaultTokens.SUB));
}
public Builder tokenReader(TokenReader tokenReader){
this.tokenReaders.add(tokenReader);
return this;
}
public Builder operator(Token token, Operator operator){
this.operators.put(token, operator);
return this;
}
public Builder valueReader(ValueReader valueReader){
this.valueReaders.add(valueReader);
return this;
}
public Options build(){
return new Options(this.tokenReaders, ImmutableMap.copyOf(operators), ImmutableList.copyOf(valueReaders));
}
}
}
}
@@ -1,238 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.*;
import java.util.Collection;
public class Expressions{
public static ToBooleanExpression negate(ToBooleanExpression expression){
return new AbstractUnaryToBooleanExpression<>(expression){
@Override
public boolean evaluate(){
return !delegate.evaluate();
}
};
}
public static ToBooleanExpression and(Collection<ToBooleanExpression> operands){
return new AbstractToBooleanExpression<>(operands){
@Override
public boolean evaluate(){
for(ToBooleanExpression operand : operands){
if(!operand.evaluate())
return false;
}
return true;
}
};
}
public static ToBooleanExpression or(Collection<ToBooleanExpression> operands){
return new AbstractToBooleanExpression<>(operands){
@Override
public boolean evaluate(){
for(ToBooleanExpression operand : operands){
if(operand.evaluate())
return true;
}
return false;
}
};
}
public static ToStringExpression concat(Collection<ToStringExpression> operands){
return new AbstractToStringExpression<>(operands){
@Override
public String evaluate(){
StringBuilder result = new StringBuilder();
for(ToStringExpression operand : operands){
result.append(operand.evaluate());
}
return result.toString();
}
};
}
public static ToBooleanExpression equal(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate().equals(b.evaluate());
}
};
}
public static ToBooleanExpression notEqual(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return !a.evaluate().equals(b.evaluate());
}
};
}
public static ToBooleanExpression equalIgnoreCase(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate().equalsIgnoreCase(b.evaluate());
}
};
}
public static ToBooleanExpression notEqualIgnoreCase(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return !a.evaluate().equalsIgnoreCase(b.evaluate());
}
};
}
public static ToBooleanExpression startsWith(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate().startsWith(b.evaluate());
}
};
}
public static ToBooleanExpression endsWith(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate().endsWith(b.evaluate());
}
};
}
public static ToBooleanExpression contains(ToStringExpression a, ToStringExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate().contains(b.evaluate());
}
};
}
public static ToBooleanExpression greaterThan(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate() > b.evaluate();
}
};
}
public static ToBooleanExpression greaterOrEqualThan(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate() >= b.evaluate();
}
};
}
public static ToBooleanExpression lessThan(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate() < b.evaluate();
}
};
}
public static ToBooleanExpression lessOrEqualThan(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToBooleanExpression<>(a, b){
@Override
public boolean evaluate(){
return a.evaluate() <= b.evaluate();
}
};
}
public static ToDoubleExpression sum(Collection<ToDoubleExpression> operands){
return new AbstractToDoubleExpression<>(operands){
@Override
public double evaluate(){
double result = 0;
for(ToDoubleExpression operand : operands){
result += operand.evaluate();
}
return result;
}
};
}
public static ToDoubleExpression product(Collection<ToDoubleExpression> operands){
return new AbstractToDoubleExpression<>(operands){
@Override
public double evaluate(){
double result = 1;
for(ToDoubleExpression operand : operands){
result *= operand.evaluate();
}
return result;
}
};
}
public static ToDoubleExpression sub(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToDoubleExpression<>(a, b){
@Override
public double evaluate(){
return a.evaluate() - b.evaluate();
}
};
}
public static ToDoubleExpression div(ToDoubleExpression a, ToDoubleExpression b){
return new AbstractBinaryToDoubleExpression<>(a, b){
@Override
public double evaluate(){
return a.evaluate() / b.evaluate();
}
};
}
public static ToDoubleExpression negateNumber(ToDoubleExpression a){
return new AbstractUnaryToDoubleExpression<>(a){
@Override
public double evaluate(){
return -delegate.evaluate();
}
};
}
}
@@ -1,62 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import java.util.ArrayList;
import java.util.List;
public class ExpressionsWarnHelper{
private final String expression;
private final List<Context> warnings = new ArrayList<>();
public ExpressionsWarnHelper(String expression){
this.expression = expression;
}
public void appendWarning(int position, String warning, Object... args){
warnings.add(new Context(position, String.format(warning, args)));
}
public boolean hasWarnings(){
return !warnings.isEmpty();
}
public void printWarnings(PluginLogger logger){
logger.warn("Encountered %d issue(s) while parsing expression '%s'", warnings.size(), expression);
for(Context warning : warnings){
if(warning.position() > -1){
logger.warn(" - At Position %d: %s", warning.position(), warning.message());
}else{
logger.warn(" - Cause: %s", warning.message());
}
}
}
public record Context(int position, String message){}
}
@@ -1,49 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
public interface ToDoubleExpression extends Expression{
double evaluate();
static ToDoubleExpression literal(double value){
return new ConstantToDoubleExpression(value);
}
class ConstantToDoubleExpression implements ToDoubleExpression{
private final double value;
public ConstantToDoubleExpression(double value){
this.value = value;
}
@Override
public double evaluate(){
return value;
}
}
}
@@ -1,49 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.expressions;
public interface ToStringExpression extends Expression{
String evaluate();
static ToStringExpression literal(String value){
return new ConstantToStringExpression(value);
}
class ConstantToStringExpression implements ToStringExpression{
private final String value;
private ConstantToStringExpression(String value){
this.value = value;
}
@Override
public String evaluate(){
return value;
}
}
}
@@ -1,56 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.operators;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
public abstract class ListOperator extends Operator{
public ListOperator(int priority){
super(priority);
}
public static ListOperator of(int priority, Function<Collection<ExpressionTemplate>, ExpressionTemplate> function){
return new ListOperator(priority){
@Override
public ExpressionTemplate createTemplate(List<ExpressionTemplate> operands){
return function.apply(operands);
}
};
}
@Override
public ExpressionTemplate createTemplate(ExpressionTemplate a, ExpressionTemplate b){
return createTemplate(Arrays.asList(a, b));
}
public abstract ExpressionTemplate createTemplate(List<ExpressionTemplate> operands);
}
@@ -1,54 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.operators;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import java.util.function.BiFunction;
public abstract class Operator{
private final int priority;
public Operator(int priority){
this.priority = priority;
}
public static Operator of(int priority, BiFunction<ExpressionTemplate, ExpressionTemplate, ExpressionTemplate> function){
return new Operator(priority){
@Override
public ExpressionTemplate createTemplate(ExpressionTemplate a, ExpressionTemplate b){
return function.apply(a, b);
}
};
}
public int getPriority(){
return priority;
}
public abstract ExpressionTemplate createTemplate(ExpressionTemplate a, ExpressionTemplate b);
}
@@ -1,45 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ConstantExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.BooleanToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public class BooleanConstantReader extends ValueReader{
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) instanceof BooleanToken){
return ConstantExpressionTemplate.of(((BooleanToken)tokenList.remove(0)).getValue());
}
return null;
}
}
@@ -1,137 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.operators.ListOperator;
import ch.andre601.advancedserverlist.core.profiles.conditions.operators.Operator;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplates;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
public class ExpressionTemplateParser{
private final ImmutableMap<Token, Operator> operators;
private final ImmutableList<ValueReader> valueReaders;
public ExpressionTemplateParser(ImmutableMap<Token, Operator> operators, ImmutableList<ValueReader> valueReaders){
this.operators = operators;
this.valueReaders = valueReaders;
}
public ExpressionTemplate parse(List<Token> tokenList, ExpressionsWarnHelper warnHelper){
List<ExpressionTemplate> parts = new ArrayList<>();
List<Operator> operators = new ArrayList<>();
try{
parts.add(read(tokenList, warnHelper));
}catch(IllegalArgumentException ex){
warnHelper.appendWarning(-1, ex.getMessage());
return null;
}
while(!tokenList.isEmpty()){
Token token = tokenList.remove(0);
Operator operator = this.operators.get(token);
if(operator == null){
warnHelper.appendWarning(-1, "Received \"%s\" but expected OPERATOR.", token);
return null;
}
operators.add(operator);
if(tokenList.isEmpty()){
warnHelper.appendWarning(-1, "Received unexpected end of input.");
return null;
}
try{
parts.add(read(tokenList, warnHelper));
}catch(IllegalArgumentException ex){
warnHelper.appendWarning(-1, ex.getMessage());
return null;
}
}
while(!operators.isEmpty()){
Operator operator = operators.get(0);
int lowest = operator.getPriority();
int start = 0;
int end = 1;
for(int i = 1; i < operators.size(); i++){
operator = operators.get(i);
if(operator.getPriority() < lowest){
lowest = operator.getPriority();
start = i;
end = i + 1;
}else
if(operator.getPriority() > lowest){
break;
}else{
end++;
}
}
operator = operators.get(start);
ExpressionTemplate replacement;
if(start + 1 == end){
replacement = operator.createTemplate(parts.get(start), parts.get(end));
}else
if(operator instanceof ListOperator listOperator){
replacement = listOperator.createTemplate(new ArrayList<>(parts.subList(start, end + 1)));
}else{
List<ExpressionTemplate> conditions = new ArrayList<>(end - start);
for(int i = start; i < end; i++)
conditions.add(operators.get(i).createTemplate(parts.get(i), parts.get(i + 1)));
replacement = ExpressionTemplates.and(conditions);
}
for(int i = start; i < end; i++){
parts.remove(start);
operators.remove(start);
}
parts.set(start, replacement);
}
return parts.get(0);
}
ExpressionTemplate read(List<Token> tokenList, ExpressionsWarnHelper warnHelper){
for(ValueReader valueReader : valueReaders){
ExpressionTemplate template = valueReader.read(this, tokenList, warnHelper);
if(template != null)
return template;
}
throw new IllegalArgumentException("Invalid Expression. Expected literal but got token \"" + tokenList.get(0).toString() + "\"");
}
}
@@ -1,52 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplates;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public class NegatedExpressionReader extends ValueReader{
private final Token tokenNegation;
public NegatedExpressionReader(Token tokenNegation){
this.tokenNegation = tokenNegation;
}
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) == tokenNegation){
tokenList.remove(0);
return ExpressionTemplates.negate(parser.read(tokenList, warnHelper));
}
return null;
}
}
@@ -1,52 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplates;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public class NegatedNumberReader extends ValueReader{
private final Token tokenNegation;
public NegatedNumberReader(Token tokenNegation){
this.tokenNegation = tokenNegation;
}
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) == tokenNegation){
tokenList.remove(0);
return ExpressionTemplates.negateNumber(parser.read(tokenList, warnHelper));
}
return null;
}
}
@@ -1,44 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ConstantExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.NumberToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public class NumberConstantReader extends ValueReader{
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) instanceof NumberToken){
return ConstantExpressionTemplate.of(((NumberToken)tokenList.remove(0)).getValue());
}
return null;
}
}
@@ -1,72 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.ArrayList;
import java.util.List;
public class ParenthesisedExpressionReader extends ValueReader{
private final Token openingParenthesis;
private final Token closingParenthesis;
public ParenthesisedExpressionReader(Token openingParenthesis, Token closingParenthesis){
this.openingParenthesis = openingParenthesis;
this.closingParenthesis = closingParenthesis;
}
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) == openingParenthesis){
int index = 0;
int cnt = 1;
do {
index += 1;
if(tokenList.size() <= index)
return null;
Token token = tokenList.get(index);
if(token == openingParenthesis){
cnt++;
}else
if(token == closingParenthesis){
cnt--;
}
}while(cnt != 0);
ExpressionTemplate result = parser.parse(new ArrayList<>(tokenList.subList(1, index)), warnHelper);
tokenList.subList(0, index + 1).clear();
return result;
}
return null;
}
}
@@ -1,45 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ConstantExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.StringToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public class StringConstantReader extends ValueReader{
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) instanceof StringToken){
return ConstantExpressionTemplate.of(((StringToken)tokenList.remove(0)).getValue());
}
return null;
}
}
@@ -1,37 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.parsers;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.util.List;
public abstract class ValueReader{
public abstract ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper);
}
@@ -1,73 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.placeholders;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
public interface Placeholder extends ExpressionTemplate{
static LiteralPlaceholderValue of(String value){
double doubleValue;
try{
doubleValue = Double.parseDouble(value);
}catch(NumberFormatException ex){
doubleValue = value.length();
}
return new LiteralPlaceholderValue(value, doubleValue, Boolean.parseBoolean(value));
}
class LiteralPlaceholderValue implements Placeholder{
private final String stringValue;
private final double doubleValue;
private final boolean booleanValue;
public LiteralPlaceholderValue(String stringValue, double doubleValue, boolean booleanValue){
this.stringValue = stringValue;
this.doubleValue = doubleValue;
this.booleanValue = booleanValue;
}
@Override
public ToStringExpression instantiateWithStringResult(){
return ToStringExpression.literal(stringValue);
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return ToDoubleExpression.literal(doubleValue);
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return ToBooleanExpression.literal(booleanValue);
}
}
}
@@ -1,117 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.placeholders;
import ch.andre601.advancedserverlist.api.AdvancedServerListAPI;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import java.text.ParsePosition;
public class PlaceholderParser{
public static Placeholder parse(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
AdvancedServerListAPI api = AdvancedServerListAPI.get();
int index = position.getIndex();
StringBuilder identifier = new StringBuilder();
StringBuilder values = new StringBuilder();
boolean identified = false;
boolean invalid = true;
char[] chars = text.substring(index).toCharArray();
for(final char c : chars){
index++;
if(c == '}'){
invalid = false;
break;
}
if(c == ' ' && !identified){
identified = true;
continue;
}
if(identified){
values.append(c);
}else{
identifier.append(c);
}
}
String identifierStr = identifier.toString();
String valuesStr = values.toString();
StringBuilder raw = new StringBuilder();
position.setIndex(index + 1);
if(invalid){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
warnHelper.appendWarning(index, "Placeholder '%s' does not have a closing bracket (}).",raw.toString());
return Placeholder.of(raw.toString());
}
PlaceholderProvider provider = api.retrievePlaceholderProvider(identifierStr);
if(provider == null){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
raw.append('}');
warnHelper.appendWarning(index, "Placeholder '%s' does not have an available PlaceholderProvider.", raw.toString());
return Placeholder.of(raw.toString());
}
String replacement = provider.parsePlaceholder(valuesStr, player, server);
if(replacement == null){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
raw.append('}');
warnHelper.appendWarning(index, "Placeholder '%s' returned a null value.", raw.toString());
return Placeholder.of(raw.toString());
}
return Placeholder.of(replacement);
}
}
@@ -23,26 +23,26 @@
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions.tokens.readers;
package ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.tokens.Token;
import ch.andre601.expressionparser.tokens.readers.TokenReader;
import java.text.ParsePosition;
public abstract class TokenReader{
public abstract class CustomTokenReader extends TokenReader{
private final int priority;
public TokenReader(int priority){
this.priority = priority;
public CustomTokenReader(int priority){
super(priority);
}
public int getPriority(){
return priority;
@Override
public Token read(String text, ParsePosition position, ParseWarnCollector collector){
return null;
}
public abstract Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper);
public abstract Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ParseWarnCollector collector);
}
@@ -23,28 +23,28 @@
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions.tokens.readers;
package ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.PlaceholderParser;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.PlaceholderToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.tokens.PlaceholderToken;
import ch.andre601.advancedserverlist.core.profiles.replacer.StringReplacer;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.tokens.Token;
import java.text.ParsePosition;
public class PlaceholderTokenReader extends TokenReader{
public class PlaceholderTokenReader extends CustomTokenReader{
public PlaceholderTokenReader(int priority){
super(priority);
}
@Override
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ParseWarnCollector collector){
if(position.getIndex() + 1 < text.length() && text.charAt(position.getIndex()) == '$' && text.charAt(position.getIndex() + 1) == '{'){
position.setIndex(position.getIndex() + 2);
return new PlaceholderToken(PlaceholderParser.parse(text, position, player, server, warnHelper));
return new PlaceholderToken(StringReplacer.parsePlaceholder(text, position, player, server, collector));
}
return null;
}
@@ -23,20 +23,22 @@
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions.parsers;
package ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.templates.ExpressionTemplate;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.PlaceholderToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.tokens.PlaceholderToken;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.parsers.ExpressionTemplateParser;
import ch.andre601.expressionparser.parsers.ValueReader;
import ch.andre601.expressionparser.templates.ExpressionTemplate;
import ch.andre601.expressionparser.tokens.Token;
import java.util.List;
public class PlaceholderReader extends ValueReader{
public class PlaceholderValueReader extends ValueReader{
@Override
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokenList, ExpressionsWarnHelper warnHelper){
if(tokenList.get(0) instanceof PlaceholderToken){
PlaceholderToken token = (PlaceholderToken)tokenList.remove(0);
public ExpressionTemplate read(ExpressionTemplateParser parser, List<Token> tokens, ParseWarnCollector collector){
if(tokens.get(0) instanceof PlaceholderToken){
PlaceholderToken token = (PlaceholderToken)tokens.remove(0);
return token.getValue();
}
return null;
@@ -23,14 +23,14 @@
*
*/
package ch.andre601.advancedserverlist.core.profiles.conditions;
package ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.tokens;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.readers.TokenReader;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.reader.CustomTokenReader;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.tokens.Token;
import ch.andre601.expressionparser.tokens.readers.TokenReader;
import com.google.common.collect.Ordering;
import java.text.ParsePosition;
@@ -38,39 +38,45 @@ import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class ExpressionTokenizer{
public class CustomExpressionTokenizer{
private static final Ordering<TokenReader> TOKEN_READER_ORDERING = Ordering.from(Comparator.comparingInt(TokenReader::getPriority)).reverse();
private final List<TokenReader> tokenReaders;
public ExpressionTokenizer(Iterable<TokenReader> tokenReaders){
public CustomExpressionTokenizer(Iterable<TokenReader> tokenReaders){
this.tokenReaders = TOKEN_READER_ORDERING.immutableSortedCopy(tokenReaders);
}
public List<Token> parse(String text, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
public List<Token> parse(String text, GenericPlayer player, GenericServer server, ParseWarnCollector collector){
ParsePosition position = new ParsePosition(0);
List<Token> tokens = new LinkedList<>();
next_token:
while(true){
while(position.getIndex() < text.length() && Character.isWhitespace(text.charAt(position.getIndex()))){
while(position.getIndex() < text.length() && Character.isWhitespace(text.charAt(position.getIndex())))
position.setIndex(position.getIndex() + 1);
}
if(position.getIndex() >= text.length())
break;
for(TokenReader tokenReader : tokenReaders){
Token token;
if(null != (token = tokenReader.read(text, position, player, server, warnHelper))){
tokens.add(token);
continue next_token;
if(tokenReader instanceof CustomTokenReader customTokenReader){
if(null != (token = customTokenReader.read(text, position, player, server, collector))){
tokens.add(token);
continue next_token;
}
}else{
if(null != (token = tokenReader.read(text, position, collector))){
tokens.add(token);
continue next_token;
}
}
}
warnHelper.appendWarning(position.getIndex(), "Illegal token '%c'.");
collector.appendWarningFormatted(position.getIndex(), "Illegal Token '%c'.", text.charAt(position.getIndex()));
break;
}
@@ -0,0 +1,81 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.placeholders.tokens;
import ch.andre601.expressionparser.expressions.ToBooleanExpression;
import ch.andre601.expressionparser.expressions.ToDoubleExpression;
import ch.andre601.expressionparser.expressions.ToStringExpression;
import ch.andre601.expressionparser.templates.ExpressionTemplate;
import ch.andre601.expressionparser.tokens.Token;
public class PlaceholderToken extends Token{
private final Placeholder value;
public PlaceholderToken(Placeholder value){
super("PLACEHOLDER");
this.value = value;
}
public Placeholder getValue(){
return value;
}
public static class Placeholder implements ExpressionTemplate{
private final ToBooleanExpression toBooleanExpression;
private final ToDoubleExpression toDoubleExpression;
private final ToStringExpression toStringExpression;
public Placeholder(String value){
double doubleValue;
try{
doubleValue = Double.parseDouble(value);
}catch(NumberFormatException ex){
doubleValue = value.length();
}
this.toBooleanExpression = ToBooleanExpression.literal(Boolean.parseBoolean(value));
this.toDoubleExpression = ToDoubleExpression.literal(doubleValue);
this.toStringExpression = ToStringExpression.literal(value);
}
@Override
public ToBooleanExpression returnBooleanExpression(){
return toBooleanExpression;
}
@Override
public ToDoubleExpression returnDoubleExpression(){
return toDoubleExpression;
}
@Override
public ToStringExpression returnStringExpression(){
return toStringExpression;
}
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
public abstract class AbstractBinaryToBooleanExpression<T extends Expression> implements ToBooleanExpression{
protected final T a;
protected final T b;
public AbstractBinaryToBooleanExpression(T a, T b){
this.a = a;
this.b = b;
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
public abstract class AbstractBinaryToDoubleExpression<T extends Expression> implements ToDoubleExpression{
protected final T a;
protected final T b;
public AbstractBinaryToDoubleExpression(T a, T b){
this.a = a;
this.b = b;
}
}
@@ -1,43 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.Conversions;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
public abstract class AbstractBooleanExpressionTemplate implements ExpressionTemplate{
@Override
public ToStringExpression instantiateWithStringResult(){
return Conversions.toString(instantiateWithBooleanResult());
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Conversions.toDouble(instantiateWithBooleanResult());
}
}
@@ -1,43 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.Conversions;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
public abstract class AbstractDoubleExpressionTemplate implements ExpressionTemplate{
@Override
public ToStringExpression instantiateWithStringResult(){
return Conversions.toString(instantiateWithDoubleResult());
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Conversions.toBoolean(instantiateWithDoubleResult());
}
}
@@ -1,43 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.Conversions;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
public abstract class AbstractStringExpressionTemplate implements ExpressionTemplate{
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Conversions.toDouble(instantiateWithStringResult());
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Conversions.toBoolean(instantiateWithStringResult());
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import java.util.Collection;
public abstract class AbstractToBooleanExpression<T extends Expression> implements ToBooleanExpression{
protected final Collection<T> operands;
public AbstractToBooleanExpression(Collection<T> operands){
this.operands = operands;
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import java.util.Collection;
public abstract class AbstractToDoubleExpression<T extends Expression> implements ToDoubleExpression{
protected final Collection<T> operands;
public AbstractToDoubleExpression(Collection<T> operands){
this.operands = operands;
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
import java.util.Collection;
public abstract class AbstractToStringExpression<T extends Expression> implements ToStringExpression{
protected Collection<T> operands;
public AbstractToStringExpression(Collection<T> operands){
this.operands = operands;
}
}
@@ -1,38 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
public abstract class AbstractUnaryToBooleanExpression<T extends Expression> implements ToBooleanExpression{
protected final T delegate;
public AbstractUnaryToBooleanExpression(T delegate){
this.delegate = delegate;
}
}
@@ -1,38 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
public abstract class AbstractUnaryToDoubleExpression<T extends Expression> implements ToDoubleExpression{
protected final T delegate;
public AbstractUnaryToDoubleExpression(T delegate){
this.delegate = delegate;
}
}
@@ -1,38 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
public abstract class AbstractUnaryToStringExpression<T extends Expression> implements ToStringExpression{
protected final T delegate;
public AbstractUnaryToStringExpression(T delegate){
this.delegate = delegate;
}
}
@@ -1,77 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
public class ConstantExpressionTemplate implements ExpressionTemplate{
private final ToStringExpression stringExpression;
private final ToDoubleExpression doubleExpression;
private final ToBooleanExpression booleanExpression;
private ConstantExpressionTemplate(String stringValue, double doubleValue, boolean booleanValue){
this.stringExpression = ToStringExpression.literal(stringValue);
this.doubleExpression = ToDoubleExpression.literal(doubleValue);
this.booleanExpression = ToBooleanExpression.literal(booleanValue);
}
public static ConstantExpressionTemplate of(String stringValue){
double doubleValue;
try{
doubleValue = Double.parseDouble(stringValue);
}catch(NumberFormatException ex){
doubleValue = stringValue.length();
}
return new ConstantExpressionTemplate(stringValue, doubleValue, Boolean.parseBoolean(stringValue));
}
public static ConstantExpressionTemplate of(double doubleValue){
return new ConstantExpressionTemplate(((int)doubleValue) == doubleValue ? Integer.toString((int)doubleValue) : Double.toString(doubleValue), doubleValue, doubleValue != 0);
}
public static ConstantExpressionTemplate of(boolean booleanValue){
return new ConstantExpressionTemplate(Boolean.toString(booleanValue), booleanValue ? 1 : 0, booleanValue);
}
@Override
public ToStringExpression instantiateWithStringResult(){
return stringExpression;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return doubleExpression;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return booleanExpression;
}
}
@@ -1,39 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
public interface ExpressionTemplate{
ToStringExpression instantiateWithStringResult();
ToDoubleExpression instantiateWithDoubleResult();
ToBooleanExpression instantiateWithBooleanResult();
}
@@ -1,422 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.templates;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.Expressions;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToBooleanExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToDoubleExpression;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ToStringExpression;
import java.util.Collection;
public class ExpressionTemplates{
public static ExpressionTemplate negate(ExpressionTemplate template){
return new Negation(template);
}
public static ExpressionTemplate and(Collection<ExpressionTemplate> operands){
return new And(operands);
}
public static ExpressionTemplate or(Collection<ExpressionTemplate> operands){
return new Or(operands);
}
public static ExpressionTemplate concat(Collection<ExpressionTemplate> operands){
return new Concatenate(operands);
}
public static ExpressionTemplate equal(ExpressionTemplate a, ExpressionTemplate b){
return new Equal(a, b);
}
public static ExpressionTemplate notEqual(ExpressionTemplate a, ExpressionTemplate b){
return new NotEqual(a, b);
}
public static ExpressionTemplate equalIgnoreCase(ExpressionTemplate a, ExpressionTemplate b){
return new EqualIgnoreCase(a, b);
}
public static ExpressionTemplate notEqualIgnoreCase(ExpressionTemplate a, ExpressionTemplate b){
return new NotEqualIgnoreCase(a, b);
}
public static ExpressionTemplate startsWith(ExpressionTemplate a, ExpressionTemplate b){
return new StartsWith(a, b);
}
public static ExpressionTemplate endsWith(ExpressionTemplate a, ExpressionTemplate b){
return new EndsWith(a, b);
}
public static ExpressionTemplate contains(ExpressionTemplate a, ExpressionTemplate b){
return new Contains(a, b);
}
public static ExpressionTemplate greater(ExpressionTemplate a, ExpressionTemplate b){
return new Greater(a, b);
}
public static ExpressionTemplate greaterOrEqual(ExpressionTemplate a, ExpressionTemplate b){
return new GreaterOrEqual(a, b);
}
public static ExpressionTemplate less(ExpressionTemplate a, ExpressionTemplate b){
return new Less(a, b);
}
public static ExpressionTemplate lessOrEqual(ExpressionTemplate a, ExpressionTemplate b){
return new LessOrEqual(a, b);
}
public static ExpressionTemplate sum(Collection<ExpressionTemplate> operands){
return new Sum(operands);
}
public static ExpressionTemplate product(Collection<ExpressionTemplate> operands){
return new Product(operands);
}
public static ExpressionTemplate sub(ExpressionTemplate a, ExpressionTemplate b){
return new Sub(a, b);
}
public static ExpressionTemplate div(ExpressionTemplate a, ExpressionTemplate b){
return new Div(a, b);
}
public static ExpressionTemplate negateNumber(ExpressionTemplate template){
return new NegationNumber(template);
}
private static class Negation extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate template;
Negation(ExpressionTemplate template){
this.template = template;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.negate(template.instantiateWithBooleanResult());
}
}
private static class And extends AbstractBooleanExpressionTemplate{
private final Collection<ExpressionTemplate> operands;
And(Collection<ExpressionTemplate> operands){
this.operands = operands;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.and(operands.stream().map(ExpressionTemplate::instantiateWithBooleanResult).toList());
}
}
private static class Or extends AbstractBooleanExpressionTemplate{
private final Collection<ExpressionTemplate> operands;
Or(Collection<ExpressionTemplate> operands){
this.operands = operands;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.or(operands.stream().map(ExpressionTemplate::instantiateWithBooleanResult).toList());
}
}
private static class Concatenate extends AbstractStringExpressionTemplate{
private final Collection<ExpressionTemplate> operands;
Concatenate(Collection<ExpressionTemplate> operands){
this.operands = operands;
}
@Override
public ToStringExpression instantiateWithStringResult(){
return Expressions.concat(operands.stream().map(ExpressionTemplate::instantiateWithStringResult).toList());
}
}
private static class Equal extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
Equal(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.equal(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class NotEqual extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
NotEqual(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.notEqual(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class EqualIgnoreCase extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
EqualIgnoreCase(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.equalIgnoreCase(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class NotEqualIgnoreCase extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
NotEqualIgnoreCase(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.notEqualIgnoreCase(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class StartsWith extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
private StartsWith(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.startsWith(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class EndsWith extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
private EndsWith(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.endsWith(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class Contains extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
private Contains(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.contains(a.instantiateWithStringResult(), b.instantiateWithStringResult());
}
}
private static class Greater extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
Greater(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.greaterThan(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class GreaterOrEqual extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
GreaterOrEqual(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.greaterOrEqualThan(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class Less extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
Less(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.lessThan(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class LessOrEqual extends AbstractBooleanExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
LessOrEqual(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToBooleanExpression instantiateWithBooleanResult(){
return Expressions.lessOrEqualThan(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class Sum extends AbstractDoubleExpressionTemplate{
private final Collection<ExpressionTemplate> operands;
Sum(Collection<ExpressionTemplate> operands){
this.operands = operands;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Expressions.sum(operands.stream().map(ExpressionTemplate::instantiateWithDoubleResult).toList());
}
}
private static class Product extends AbstractDoubleExpressionTemplate{
private final Collection<ExpressionTemplate> operands;
Product(Collection<ExpressionTemplate> operands){
this.operands = operands;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Expressions.product(operands.stream().map(ExpressionTemplate::instantiateWithDoubleResult).toList());
}
}
private static class Sub extends AbstractDoubleExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
Sub(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Expressions.sub(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class Div extends AbstractDoubleExpressionTemplate{
private final ExpressionTemplate a;
private final ExpressionTemplate b;
Div(ExpressionTemplate a, ExpressionTemplate b){
this.a = a;
this.b = b;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Expressions.div(a.instantiateWithDoubleResult(), b.instantiateWithDoubleResult());
}
}
private static class NegationNumber extends AbstractDoubleExpressionTemplate{
private final ExpressionTemplate template;
NegationNumber(ExpressionTemplate template){
this.template = template;
}
@Override
public ToDoubleExpression instantiateWithDoubleResult(){
return Expressions.negateNumber(template.instantiateWithDoubleResult());
}
}
}
@@ -1,42 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens;
public class BooleanToken extends Token{
public static final BooleanToken TRUE = new BooleanToken(true);
public static final BooleanToken FALSE = new BooleanToken(false);
private final boolean value;
public BooleanToken(boolean value){
super("BOOLEAN(" + value + ")");
this.value = value;
}
public boolean getValue(){
return value;
}
}
@@ -1,50 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens;
public class DefaultTokens{
public static final Token AND = new Token("AND");
public static final Token OR = new Token("OR");
public static final Token OPENING_PARENTHESIS = new Token("OPENING_PARENTHESIS");
public static final Token CLOSING_PARENTHESIS = new Token("CLOSING_PARENTHESIS");
public static final Token EQUAL = new Token("EQUAL");
public static final Token NOT_EQUAL = new Token("NOT_EQUAL");
public static final Token EQUAL_IGNORE_CASE = new Token("EQUAL_IGNORE_CASE");
public static final Token NOT_EQUAL_IGNORE_CASE = new Token("NOT_EQUAL_IGNORE_CASE");
public static final Token STARTS_WITH = new Token("STARTS_WITH");
public static final Token ENDS_WITH = new Token("ENDS_WITH");
public static final Token CONTAINS = new Token("CONTAINS");
public static final Token NEGATION = new Token("NEGATION");
public static final Token GREATER_THAN = new Token("GREATER_THAN");
public static final Token GREATER_OR_EQUAL_THAN = new Token("GREATER_OR_EQUAL_THAN");
public static final Token LESSER_THAN = new Token("LESSER_THAN");
public static final Token LESSER_OR_EQUAL_THAN = new Token("LESSER_OR_EQUAL_THAN");
public static final Token CONCAT_STRING = new Token("CONCAT_STRING");
public static final Token ADD = new Token("ADD");
public static final Token SUB = new Token("SUB");
public static final Token MULT = new Token("MULT");
public static final Token DIV = new Token("DIV");
}
@@ -1,42 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.Placeholder;
public class PlaceholderToken extends Token{
private final Placeholder value;
public PlaceholderToken(Placeholder value){
super("PLACEHOLDER");
this.value = value;
}
public Placeholder getValue(){
return value;
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens;
public class StringToken extends Token{
private final String value;
public StringToken(String value){
super("STRING(" + value + ")");
this.value = value;
}
public String getValue(){
return value;
}
}
@@ -1,40 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens;
public class Token{
private final String id;
public Token(String id){
this.id = id;
}
@Override
public String toString(){
return id;
}
}
@@ -1,54 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens.readers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.StringToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.text.ParsePosition;
public class NonQuotedLiteralTokenReader extends TokenReader{
public NonQuotedLiteralTokenReader(int priority){
super(priority);
}
@Override
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
int startIndex = position.getIndex();
int index = position.getIndex();
while(++index < text.length() && !Character.isWhitespace(text.charAt(index)))
;
position.setIndex(index);
return new StringToken(text.substring(startIndex, position.getIndex()));
}
}
@@ -1,56 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens.readers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.NumberToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;
public class NumberTokenReader extends TokenReader{
private final NumberFormat format = NumberFormat.getInstance(Locale.ROOT);
public NumberTokenReader(int priority){
super(priority);
}
@Override
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
int previous = position.getIndex();
Number number = format.parse(text, position);
if(position.getIndex() != previous)
return new NumberToken(number.doubleValue());
return null;
}
}
@@ -1,62 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens.readers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.text.ParsePosition;
public class PatternTokenReader extends TokenReader{
private final Token token;
private final String pattern;
private final boolean ignoreCase;
public PatternTokenReader(Token token, String pattern){
this(token, pattern, true);
}
public PatternTokenReader(Token token, String pattern, boolean ignoreCase){
super(pattern.length());
this.token = token;
this.pattern = pattern;
this.ignoreCase = ignoreCase;
}
@Override
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
if(text.regionMatches(ignoreCase, position.getIndex(), pattern, 0, pattern.length())){
position.setIndex(position.getIndex() + pattern.length());
return token;
}
return null;
}
}
@@ -1,63 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2022-2024 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.tokens.readers;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.StringToken;
import ch.andre601.advancedserverlist.core.profiles.conditions.tokens.Token;
import java.text.ParsePosition;
public class QuotedLiteralTokenReader extends TokenReader{
private final char quote;
public QuotedLiteralTokenReader(int priority, char quote){
super(priority);
this.quote = quote;
}
@Override
public Token read(String text, ParsePosition position, GenericPlayer player, GenericServer server, ExpressionsWarnHelper warnHelper){
if(position.getIndex() < text.length() && text.charAt(position.getIndex()) == quote){
int startIndex = position.getIndex();
position.setIndex(position.getIndex() + 1);
while(position.getIndex() < text.length() && quote != text.charAt(position.getIndex()))
position.setIndex(position.getIndex() + 1);
position.setIndex(position.getIndex() + 1);
return new StringToken(text.substring(startIndex + 1, position.getIndex() - 1));
}
return null;
}
}
@@ -26,145 +26,167 @@
package ch.andre601.advancedserverlist.core.profiles.favicon;
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 javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Stream;
public class FaviconHandler<F>{
private final Cache<String, CompletableFuture<F>> favicons = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
private final AdvancedServerList<F> core;
private final PluginLogger logger;
private final ThreadPoolExecutor faviconThreadPool;
private final Cache<String, CompletableFuture<F>> faviconCache;
private final Map<String, F> localFavicons = new HashMap<>();
private final HttpClient client = HttpClient.newHttpClient();
public FaviconHandler(AdvancedServerList<F> core){
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();
loadLocalFavicons();
}
public F getFavicon(String input, Function<BufferedImage, F> function){
public F getFavicon(String input){
if(localFavicons.containsKey(input.toLowerCase(Locale.ROOT).split("\\.")[0])){
return localFavicons.get(input.toLowerCase(Locale.ROOT).split("\\.")[0]);
}
try{
return favicons.get(input, () -> convert(input, function)).getNow(null);
}catch(ExecutionException e){
return faviconCache.get(input, () -> getFuture(input)).getNow(null);
}catch(ExecutionException ex){
logger.warn("Received ExecutionException while retrieving Favicon for '%s'.", ex, input);
return null;
}
}
public void clearCache(){
favicons.invalidateAll();
public void cleanCache(){
faviconCache.invalidateAll();
loadLocalFavicons();
}
private CompletableFuture<F> convert(String input, Function<BufferedImage, F> function){
return CompletableFuture.supplyAsync(() -> {
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Getting BufferedImage for input '%s'...", input);
BufferedImage img = resolveImage(core, input);
if(img == null){
core.getPlugin().getPluginLogger().debugWarn(FaviconHandler.class, "No BufferedImage could be created!");
return null;
}
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Received BufferedImage! Applying it...");
return function.apply(img);
}, faviconThreadPool);
}
private BufferedImage resolveImage(AdvancedServerList<F> core, String input){
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Resolving favicon for input '%s'...", input);
InputStream stream;
private CompletableFuture<F> getFuture(String input){
if(input.toLowerCase(Locale.ROOT).startsWith("https://")){
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "URL detected. Getting file from it...");
stream = getFromUrl(core, input);
logger.debug(FaviconHandler.class, "Resolving URL '%s'...", input);
return CompletableFuture.supplyAsync(() -> fromURL(core, input), this.faviconThreadPool);
}else
if(input.toLowerCase(Locale.ROOT).endsWith(".png")){
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Image file detected. Trying to reolve it...");
File folder = core.getPlugin().getFolderPath().resolve("favicons").toFile();
if(!folder.exists()){
core.getPlugin().getPluginLogger().warn("Cannot get Favicon %s from favicons folder. Folder doesn't exist!", input);
return null;
}
File file = new File(folder, input);
try{
stream = new FileInputStream(file);
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Resolved image file!");
}catch(IOException ex){
core.getPlugin().getPluginLogger().warn("Cannot create Favicon from File %s.", input);
core.getPlugin().getPluginLogger().warn("Cause: %s", ex.getMessage());
return null;
}
logger.debug(FaviconHandler.class, "Resolving image file '%s'...", input);
return CompletableFuture.completedFuture(localFavicons.get(input.toLowerCase(Locale.ROOT).split("\\.")[0]));
}else{
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Possible player name/UUID detected. Using https://mc-heads.net/avatar/%s/64...", input);
stream = getFromUrl(core, "https://mc-heads.net/avatar/" + input + "/64");
logger.debug(FaviconHandler.class, "Resolving Name/UUID as https://mc-heads.net/avatar/%s/64...", input);
return CompletableFuture.supplyAsync(() -> fromURL(core, "https://mc-heads.net/avatar/" + input + "/64"), this.faviconThreadPool);
}
}
private void loadLocalFavicons(){
this.localFavicons.clear();
logger.info("Loading local image files as Favicons...");
Path folder = core.getPlugin().getFolderPath().resolve("favicons");
if(!Files.exists(folder)){
try{
Files.createDirectories(folder);
logger.info("Created favicons folder.");
}catch(IOException ex){
logger.warn("Cannot create favicons folder. Encountered an IOException.", ex);
return;
}
}
if(stream == null){
core.getPlugin().getPluginLogger().warn("Cannot create Favicon. InputStream was null.");
return null;
try(Stream<Path> pathStream = Files.list(folder)){
pathStream.filter(Files::isRegularFile)
.filter(file -> file.getFileName().toString().endsWith(".png"))
.forEach(this::loadFile);
}catch(IOException ex){
logger.warn("Cannot load files from Favicons folder.", ex);
}
try{
BufferedImage original = ImageIO.read(stream);
if(original == null){
core.getPlugin().getPluginLogger().warn("Cannot create Favicon. Unable to create BufferedImage.");
return null;
}
private void loadFile(Path path){
try(InputStream stream = Files.newInputStream(path)){
F favicon = createFavicon(stream);
if(favicon == null){
logger.warn("Cannot create Favicon from file '%s'. Received Favicon was null.", path.getFileName().toString());
return;
}
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Resizing image to 64x64 pixels...");
BufferedImage favicon = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D img = favicon.createGraphics();
// Resize original image to 64x64 and apply to favicon.
img.drawImage(original, 0, 0, 64, 64, null);
img.dispose();
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Image resized!");
return favicon;
localFavicons.put(path.getFileName().toString().split("\\.")[0], favicon);
logger.info("Loaded file '%s' as Favicon.", path.getFileName().toString());
}catch(IOException ex){
core.getPlugin().getPluginLogger().warn("Unable to create Favicon. Encountered IOException during creation.");
core.getPlugin().getPluginLogger().warn("Cause: %s", ex.getMessage());
logger.warn("Cannot create Favicon from file '%s'. Encountered IOException.", ex);
}
}
private F fromURL(AdvancedServerList<F> core, String url){
try{
logger.debug(FaviconHandler.class, "Creating Request for URL '%s'...", url);
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
.header("User-Agent", "AdvancedServerList-" + core.getPlugin().getLoader() + "/" + core.getVersion())
.build();
try(InputStream stream = client.send(request, HttpResponse.BodyHandlers.ofInputStream()).body()){
return createFavicon(stream);
}catch(InterruptedException | IOException ex){
logger.warn("Cannot create Favicon from URL '%s'. Encountered an Exception.", ex, url);
return null;
}
}catch(URISyntaxException ex){
logger.warn("Cannot create Favicon from URL '%s'. Encountered an IOException.", ex, url);
return null;
}
}
private InputStream getFromUrl(AdvancedServerList<F> core, String url){
private F createFavicon(InputStream stream){
try{
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "Resolving URL '%s'...", url);
logger.debug(FaviconHandler.class, "Creating BufferedImage from InputStream...");
BufferedImage original = ImageIO.read(stream);
if(original == null){
logger.warn("Cannot create Favicon. Received null BufferedImage.");
return null;
}
URL faviconUrl = new URL(url);
URLConnection connection = faviconUrl.openConnection();
connection.setRequestProperty("User-Agent", "AdvancedServerList/" + core.getVersion());
connection.connect();
// Don't waste resources resizing images already having right size.
if(original.getWidth() == 64 && original.getHeight() == 64){
logger.debug(FaviconHandler.class, "BufferedImage is 64x64 pixels. No resizing needed.");
return core.getPlugin().createFavicon(original);
}
core.getPlugin().getPluginLogger().debug(FaviconHandler.class, "URL resolved!");
return connection.getInputStream();
}catch(IOException ex){
core.getPlugin().getPluginLogger().warn("Error while connecting to %s for Favicon creation.", url);
core.getPlugin().getPluginLogger().warn("Cause: %s", ex.getMessage());
logger.debug(FaviconHandler.class, "Resizing image to 64x64 pixels...");
BufferedImage image = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = image.createGraphics();
graphics2D.drawImage(original, 0, 0, 64, 64, null);
graphics2D.dispose();
logger.debug(FaviconHandler.class, "Image resized! Returning Favicon...");
return core.getPlugin().createFavicon(image);
}catch(Exception ex){
logger.warn("Unable to create Favicon. Received Exception.", ex);
return null;
}
}
@@ -29,6 +29,8 @@ import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.interfaces.PluginLogger;
import ch.andre601.advancedserverlist.core.objects.CachedPlayer;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import io.leangen.geantyref.TypeToken;
import java.io.BufferedReader;
@@ -38,7 +40,9 @@ import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class PlayerHandler{
@@ -68,19 +72,18 @@ public class PlayerHandler{
}
if(core.getFileHandler().getBoolean("disableCache")){
logger.info("'disable_cache' is set to true. Skipping playercache.json loading...");
logger.info("'disableCache' is set to true. Skipping playercache.json loading...");
return;
}
try{
BufferedReader reader = Files.newBufferedReader(cache);
try(BufferedReader reader = Files.newBufferedReader(cache)){
cachedPlayers = gson.fromJson(reader, listType);
reader.close();
}catch(IOException ex){
logger.warn("Encountered IOException while reading the playercache.json file!", ex);
return;
}catch(JsonIOException | JsonSyntaxException ex){
logger.warn("Encountered Json exception while parsing playercache.json file!", ex);
return;
}
// In case Gson messes up... I guess.
@@ -127,7 +130,7 @@ public class PlayerHandler{
return getDefaultPlayer();
for(CachedPlayer player : cachedPlayers){
if(player.getIp().equals(key))
if(player.ip().equals(key))
return player;
}
@@ -136,7 +139,7 @@ public class PlayerHandler{
public CachedPlayer getCachedPlayer(UUID uuid){
for(CachedPlayer player : cachedPlayers){
if(player.getUuid().equals(uuid))
if(player.uuid().equals(uuid))
return player;
}
@@ -150,7 +153,7 @@ public class PlayerHandler{
private boolean contains(String ip){
for(CachedPlayer player : cachedPlayers){
if(player.getIp().equals(ip))
if(player.ip().equals(ip))
return true;
}
@@ -28,9 +28,9 @@ package ch.andre601.advancedserverlist.core.profiles.profile;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.api.objects.NullBool;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.profiles.ServerListProfile;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
@@ -67,7 +67,7 @@ public class ProfileManager{
if(profile.isInvalidProfile())
continue;
if(profile.evalConditions(core.getExpressionEngine(), core.getPlugin().getPluginLogger(), player, server))
if(profile.evalConditions(core.getParser(), core.getPlugin().getPluginLogger(), player, server))
return profile;
}
@@ -86,15 +86,15 @@ public class ProfileManager{
Integer maxPlayers = resolveNullableInt(node, "playerCount", "maxPlayers", "amount");
return new ProfileEntry.Builder()
.setMotd(motd)
.setPlayers(players)
.setPlayerCountText(playerCountText)
.setFavicon(favicon)
.setHidePlayersEnabled(hidePlayers)
.setExtraPlayersEnabled(extraPlayersEnabled)
.setMaxPlayersEnabled(maxPlayersEnabled)
.setExtraPlayersCount(extraPlayers)
.setMaxPlayersCount(maxPlayers)
.motd(motd)
.players(players)
.playerCountText(playerCountText)
.favicon(favicon)
.hidePlayersEnabled(hidePlayers)
.extraPlayersEnabled(extraPlayersEnabled)
.maxPlayersEnabled(maxPlayersEnabled)
.extraPlayersCount(extraPlayers)
.maxPlayersCount(maxPlayers)
.build();
}
@@ -25,11 +25,11 @@
package ch.andre601.advancedserverlist.core.profiles.profile;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import ch.andre601.advancedserverlist.api.profiles.ProfileEntry;
import java.lang.reflect.Type;
@@ -29,6 +29,11 @@ import ch.andre601.advancedserverlist.api.AdvancedServerListAPI;
import ch.andre601.advancedserverlist.api.PlaceholderProvider;
import ch.andre601.advancedserverlist.api.objects.GenericPlayer;
import ch.andre601.advancedserverlist.api.objects.GenericServer;
import ch.andre601.advancedserverlist.core.AdvancedServerList;
import ch.andre601.advancedserverlist.core.profiles.conditions.placeholders.tokens.PlaceholderToken;
import ch.andre601.expressionparser.ParseWarnCollector;
import java.text.ParsePosition;
public class StringReplacer{
@@ -36,99 +41,113 @@ public class StringReplacer{
if(input == null)
return null;
char[] chars = input.toCharArray();
ParsePosition position = new ParsePosition(0);
StringBuilder builder = new StringBuilder(input.length());
StringBuilder identifier = new StringBuilder();
StringBuilder placeholder = new StringBuilder();
AdvancedServerListAPI api = AdvancedServerListAPI.get();
for(int i = 0; i < chars.length; i++){
char c = chars[i];
char next = (i == (chars.length - 1)) ? '\0' : chars[i + 1];
if(c != '$' || i + 2 >= chars.length){
builder.append(c);
while(position.getIndex() < input.length()){
if(position.getIndex() + 1 < input.length() && input.charAt(position.getIndex()) == '$' && input.charAt(position.getIndex() + 1) == '{'){
position.setIndex(position.getIndex() + 2);
builder.append(parsePlaceholder0(input, position, player, server, null));
continue;
}
if(next != '{'){
if(next == '\0')
continue;
builder.append(next);
i++;
continue;
}
i++;
boolean identified = false;
boolean invalid = true;
while(++i < chars.length){
final char id = chars[i];
if(id == '}'){
invalid = false;
break;
}
if(id == ' ' && !identified){
identified = true;
continue;
}
if(identified){
placeholder.append(id);
}else{
identifier.append(id);
}
}
String identifierString = identifier.toString();
String placeholderString = placeholder.toString();
identifier.setLength(0);
placeholder.setLength(0);
if(invalid){
builder.append("${").append(identifierString);
if(identified){
builder.append(' ').append(placeholderString);
}
continue;
}
PlaceholderProvider provider = api.retrievePlaceholderProvider(identifierString);
if(provider == null){
builder.append("${").append(identifierString);
if(identified){
builder.append(' ').append(placeholderString);
}
builder.append('}');
continue;
}
String replacement = provider.parsePlaceholder(placeholderString, player, server);
if(replacement == null){
builder.append("${").append(identifierString);
if(identified){
builder.append(' ').append(placeholderString);
}
builder.append('}');
continue;
}
builder.append(replacement);
builder.append(input.charAt(position.getIndex()));
position.setIndex(position.getIndex() + 1);
}
return builder.toString();
}
public static PlaceholderToken.Placeholder parsePlaceholder(String input, ParsePosition position, GenericPlayer player, GenericServer server, ParseWarnCollector collector){
return new PlaceholderToken.Placeholder(parsePlaceholder0(input, position, player, server, collector));
}
private static String parsePlaceholder0(String input, ParsePosition position, GenericPlayer player, GenericServer server, ParseWarnCollector collector){
AdvancedServerListAPI api = AdvancedServerList.getApi();
int placeholderStart = position.getIndex() - 2;
int index = position.getIndex();
StringBuilder identifier = new StringBuilder();
StringBuilder values = new StringBuilder();
boolean identified = false;
boolean invalid = true;
char[] chars = input.substring(index).toCharArray();
for(final char c : chars){
index++;
if(c == '}'){
invalid = false;
break;
}
if(c == ' ' && !identified){
identified = true;
continue;
}
if(identified){
values.append(c);
}else{
identifier.append(c);
}
}
String identifierStr = identifier.toString();
String valuesStr = values.toString();
StringBuilder raw = new StringBuilder();
// Condition parsing needs one extra increase of index... for some reason
if(collector != null)
index++;
position.setIndex(index);
if(invalid){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
if(collector != null)
collector.appendWarningFormatted(placeholderStart, "Placeholder '%s' does not have a closing bracket (})", raw.toString());
return raw.toString();
}
PlaceholderProvider provider = api.retrievePlaceholderProvider(identifierStr);
if(provider == null){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
raw.append('}');
if(collector != null)
collector.appendWarningFormatted(placeholderStart, "Placeholder '%s' does not have any available PlaceholderProvider", raw.toString());
return raw.toString();
}
String replacement = provider.parsePlaceholder(valuesStr, player, server);
if(replacement == null){
raw.append("${").append(identifierStr);
if(identified)
raw.append(' ').append(valuesStr);
raw.append('}');
if(collector != null)
collector.appendWarningFormatted(placeholderStart, "Placeholder '%s' has an invalid value String '%s'", raw.toString(), valuesStr);
return raw.toString();
}
return replacement;
}
}
+8
View File
@@ -42,6 +42,14 @@ checkUpdates: true
#
debug: false
#
# Sets the time in minutes for favicons to be cached.
# The number cannot be less than 1.
#
# Defaults to 1 if not set.
#
faviconCacheTime: 1
#
# DO NOT EDIT!
#
@@ -25,8 +25,9 @@
package ch.andre601.advancedserverlist.test;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionEngine;
import ch.andre601.advancedserverlist.core.profiles.conditions.expressions.ExpressionsWarnHelper;
import ch.andre601.advancedserverlist.core.profiles.conditions.ProfileConditionParser;
import ch.andre601.expressionparser.ParseWarnCollector;
import ch.andre601.expressionparser.templates.ExpressionTemplate;
import org.junit.jupiter.api.Test;
import java.util.Map;
@@ -35,7 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
public class ExpressionParserTests{
private final ExpressionEngine expressionEngine = new ExpressionEngine();
private final ProfileConditionParser parser = ProfileConditionParser.create();
private final DummyPluginLogger logger = new DummyPluginLogger();
private final Map<String, Boolean> testValuesMap = getTestMap();
@@ -44,8 +45,15 @@ public class ExpressionParserTests{
for(Map.Entry<String, Boolean> values : testValuesMap.entrySet()){
logger.info("TEST[expression=\"%s\", expected=%b]", values.getKey(), values.getValue());
ExpressionsWarnHelper warnHelper = new ExpressionsWarnHelper(values.getKey());
boolean result = expressionEngine.compile(values.getKey(), null, null, warnHelper).instantiateWithBooleanResult().evaluate();
ParseWarnCollector collector = new ParseWarnCollector(values.getKey());
ExpressionTemplate template = parser.compile(values.getKey(), null, null, collector);
boolean result;
if(template == null){
result = false;
}else{
result = template.returnBooleanExpression().evaluate();
}
logger.info("Result (output, isExpected): " + result + ", " + (result == values.getValue()));
assertEquals(result, values.getValue());
}
+7 -7
View File
@@ -8,28 +8,28 @@
Object summaries
-->
{% if page.meta.constructors %}
{{ info.summary('Constructor Summary', page.meta.constructors, details_type='constructor') }}
{{ info.summary('Constructor Summary', page.meta.constructors, details_type='constructor', defaults=page.meta.defaults) }}
{% endif %}
{% if page.meta.classes %}
{{ info.summary('Class Summary', page.meta.classes, details_type='class') }}
{{ info.summary('Class Summary', page.meta.classes, details_type='class', defaults=page.meta.defaults) }}
{% endif %}
{% if page.meta.enums %}
{{ info.summary('Enum Constant Summary', page.meta.enums, details_type='enum') }}
{{ info.summary('Enum Constant Summary', page.meta.enums, details_type='enum', defaults=page.meta.defaults) }}
{% endif %}
{% if page.meta.methods or page.meta.inherits %}
{{ info.summary('Method Summary', page.meta.methods, page.meta.inherits, details_type='method') }}
{{ info.summary('Method Summary', page.meta.methods, page.meta.inherits, details_type='method', defaults=page.meta.defaults) }}
{% endif %}
<!--
Detailed object info
-->
{% if page.meta.constructors %}
{{ info.info('Constructor Detail', page.meta.constructors) }}
{{ info.info('Constructor Detail', page.meta.constructors, defaults=page.meta.defaults) }}
{% endif %}
{% if page.meta.enums %}
{{ info.info('Enum Constant Detail', page.meta.enums, true) }}
{{ info.info('Enum Constant Detail', page.meta.enums, true, defaults=page.meta.defaults) }}
{% endif %}
{% if page.meta.methods %}
{{ info.info('Method Detail', page.meta.methods)}}
{{ info.info('Method Detail', page.meta.methods, defaults=page.meta.defaults)}}
{% endif %}
{% endif %}
{% endblock %}
+12 -2
View File
@@ -1,4 +1,4 @@
{% macro summary(title, summaries, inherits, details_type = 'unknown') -%}
{% macro summary(title, summaries, inherits, details_type = 'unknown', defaults = []) -%}
<h2 id="{{ title | lower() | replace(' ', '-') | e}}">
{{ title }}
</h2>
@@ -28,6 +28,8 @@
{% if summary.type and summary.type.name %}
{% set modifiers.name = modifiers.name ~ summary.type.name %}
{% elif defaults and defaults.type and defaults.type.name %}
{% set modifiers.name = modifiers.name ~ defaults.type.name %}
{% else %}
{% set modifiers.name = modifiers.name ~ "void" %}
{% endif %}
@@ -103,7 +105,7 @@
</div>
{%- endmacro %}
{% macro info(title, details, enum = false) -%}
{% macro info(title, details, enum = false, defaults = []) -%}
<h2 id="{{ title | lower() | replace(' ', '-') | e}}">
{{ title }}
</h2>
@@ -144,6 +146,14 @@
{% else %}
<span class="api-type__{{- detail.type.type | default('primitive') -}}">{{ detail.type.name | default('void') | e }}</span>
{% endif %}
{% elif defaults and defaults.type %}
{% if defaults.type.link %}
<a href="{{ defaults.type.link }}" class="api-type__{{- defaults.type.type | default('primitive') -}}">{{ defaults.type.name | default('void') | e }}</a>
{% else %}
<span class="api-type__{{- defaults.type.type | default('primitive') -}}">{{ defaults.type.name | default('void') }}</span>
{% endif %}
{% else %}
<span class="api-type__primitive">void</span>
{% endif %}
<code>{{ final_name.name | e }}</code><a href="#{{ final_name.name | lower() | replace(' ', '-') | e }}" class="headerlink" title="Permanent link"></a>
</h3>
+20
View File
@@ -32,6 +32,26 @@ Placeholders for the plugin [AdvancedBan](https://www.spigotmc.org/resources/869
An optional Date and time Pattern can be set to change the displayed output. The default is `dd, MMM yyyy HH:mm:ss`.
Example: `${advancedban banExpiration yyyy-MM-dd HH:mm:ss}`
### LibertyBans
Placeholders for the plugin [LibertyBans](https://modrinth.com/plugin/libertybans/){ target="_blank" rel="nofollow" } are available to use.
| Placeholder | Description |
|---------------------------------|------------------------------------------------------------------------------------------|
| `${libertybans isMuted}` | Whether the player is muted or not. |
| `${libertybans muteReason}` | The reason for why the player was muted. Returns invalid placeholder if no mute was set. |
| `${libertybans muteExpiration}` | Date on when the mute will expire.[^5] |
| `${libertybans isBanned}` | Whether the player is banned or not. |
| `${libertybans banReason}` | The reason for why the player was banned. Returns invalid placeholder if no ban was set. |
| `${libertybans banExpiration}` | Date on when the ban will expire.[^6] |
[^5]:
An optional Date and time Pattern can be set to change the displayed output. The default is `dd, MMM yyyy HH:mm:ss`.
Example: `${libertybans muteExpiration yyyy-MM-dd HH:mm:ss}`
[^6]:
An optional Date and time Pattern can be set to change the displayed output. The default is `dd, MMM yyyy HH:mm:ss`.
Example: `${libertybans banExpiration yyyy-MM-dd HH:mm:ss}`
## Example
```yaml title="banned.yml"
+80 -1
View File
@@ -7,6 +7,85 @@ icon: octicons/log-24
This page lists the recent changes made towards the AdvancedServerListAPI.
They are ordered newest to oldest.
## v3.2.1 { #v3.2.1 }
### :octicons-pencil-24:{ .changelog-changed title="Changed" } Changed { #v3.2.1-changed }
- Removed usage of `${api.version}` in the different pom.xml for version resolving.
## v3.2.0 { #v3.2.0 }
### :octicons-plus-circle-24:{ .changelog-added title="Added" } Added { #v3.2.0-added }
- New setter methods added to [`ProfileEntry.Builder`][profileentry.builder] class, replacing old ones (See deprecations below):
- [`extraPlayersCount(Integer)`][extraplayerscount]
- [`extraPlayersEnabled(NullBool)`][extraplayersenabled]
- [`favicon(String)`][favicon]
- [`hidePlayersEnabled(NullBool)`][hideplayersenabled]
- [`maxPlayersCount(Integer)`][maxplayerscount]
- [`maxPlayersEnabled(NullBool)`][maxplayersenabled]
- [`motd(List<String>)`][motd]
- [`playerCountText(String)`][playercounttext]
- [`players(List<String>)`][players]
[extraplayerscount]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#extraplayerscount(integer)
[extraplayersenabled]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#extraplayersenabled(nullbool)
[favicon]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#favicon(string)
[hideplayersenabled]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#hideplayersenabled(nullbool)
[maxplayerscount]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#maxplayerscount(integer)
[maxplayersenabled]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#maxplayersenabled(nullbool)
[motd]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#motd(list<string>)
[playercounttext]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#playercounttext(string)
[players]: reference/api/ch.andre601.advancedserverlist.api/profiles/profileentry/builder.md#players(list<string>)
### :octicons-pencil-24:{ .changelog-changed title="Changed" } Changed { #v3.2.0-changed }
- The API has been moved to Codeberg and is now available under a new repository URL to download. The group and artifact ID remained the same, but version no longer has a `v` prefix:
/// tab | ":simple-apachemaven: Maven (pom.xml)"
```xml
<repositories>
<repository>
<id>codeberg</id>
<url>https://codeberg.org/api/packages/Andre601/maven/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>ch.andre601.asl-api</groupId>
<artifactId>api</artifactId>
<version>{apiVersion}</version>
<scope>provided</scope>
</dependency>
</dependencies>
```
///
/// tab | ":simple-gradle: Gradle (build.gradle)"
```groovy
repositories {
maven = { url ="https://codeberg.org/api/packages/Andre601/maven/" }
}
dependencies {
compileOnly "ch.andre601.asl-api:api:{apiVersion}"
}
```
///
### :octicons-zap-24:{ .changelog-breaking title="Deprecated" } Deprecated { #v3.2.0-deprecated }
- Setters in [`ProfileEntry.Builder`][profileentry.builder] deprecated in favour of more consistent method naming.
- `setExtraPlayersCount(Integer)`
- `setExtraPlayersEnabled(NullBool)`
- `setFavicon(String)`
- `setHidePlayersEnabled(NullBool)`
- `setMaxPlayersCount(Integer)`
- `setMaxPlayersEnabled(NullBool)`
- `setMotd(List<String>)`
- `setPlayerCountText(String)`
- `setPlayers(List<String>)`
## v3.1.0 { #v3.1.0 }
### :octicons-plus-circle-24:{ .changelog-added title="Added" } Added { #v3.1.0-added }
@@ -111,6 +190,6 @@ Templates for changelog
### :octicons-plus-circle-24:{ .changelog-added title="Added" } Added { #v-added }
### :octicons-pencil-24:{ .changelog-changed title="Changed" } Changed { #v-changed }
### :octicons-trash-24:{ .changelog-removed title="Removed" } Removed { #v-removed }
### :octicons-zap-24:{ .changelog-deprecated title="Deprecated" } Deprecated { #v-deprecated }
### :octicons-zap-24:{ .changelog-breaking title="Deprecated" } Deprecated { #v-deprecated }
-->
+5 -6
View File
@@ -4,8 +4,7 @@ icon: octicons/command-palette-24
# API
AdvancedServerList v2 introduced a new API that plugins can hook into to use.
It provides a way for your plugin to provide its own placeholders that should be parsed by AdvancedServerList and also an event to modify the server list.
AdvancedServerList offers an API that other plugins can use to add their own placeholder to the plugin, listen for specific events or even modify Server List Profiles on the fly.
## Add dependency
@@ -15,8 +14,8 @@ Add the following to your `pom.xml`, `build.gradle` or `build.gradle.kts` depend
```xml title="pom.xml"
<repositories>
<repository>
<id>jitpack</id>
<url>https://jitpack.io/</url>
<id>codeberg</id>
<url>https://codeberg.org/api/packages/Andre601/maven/</url>
</repository>
</repositories>
@@ -54,7 +53,7 @@ Add the following to your `pom.xml`, `build.gradle` or `build.gradle.kts` depend
/// tab | :simple-gradle: Gradle
```groovy title="build.gradle"
repositorories {
maven { url = 'https://jitpack.io/' }
maven { url = 'https://codeberg.org/api/packages/Andre601/maven/' }
}
dependencies {
@@ -71,7 +70,7 @@ dependencies {
/// tab | :simple-gradle: Gradle (KTS)
```kotlin title="build.gradle.kts"
repositories {
maven("https://jitpack.io")
maven("https://codeberg.org/api/packages/Andre601/maven/")
}
dependencies {
+1 -1
View File
@@ -1,7 +1,7 @@
---
template: redirect.html
location: https://docs.andre601.ch/asl-api
location: https://jd.andre601.ch
title: Javadocs
icon: octicons/link-external-24
@@ -1,59 +1,213 @@
---
template: api-doc.html
defaults:
type:
name: 'Builder'
type: 'object'
constructors:
- name: 'Builder'
description: 'Empty Builder Constructor used to create a new instance of this class.'
methods:
- name: 'setMotd'
- name: 'extraPlayersCount'
description: |
Sets the number of players to add to the online players to use as the new max players value.<br>
This option has no effect when <a href="../#extraplayersenabled()"><code>extraPlayersEnabled</code></a> is set to <a href="../../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively, set <a href="#setextraplayersenabled(nullbool)"><code>setExtraPlayersEnabled(NullBool)</code></a> to <a href="../../../objects/nullbool/#false"><code>NullBool.FALSE</code></a>.
parameters:
- name: 'extraPlayersCount'
description: 'The number of extra players to add.'
type: 'Integer'
attribute:
- 'nullable'
returns: 'This Builder after the extra player count has been set. Useful for chaining.'
- name: 'extraPlayersEnabled'
description: |
Sets whether the extra players feature should be enabled or not.<br>
<br>
Set to <a href="../../../objects/nullbool#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
parameters:
- name: 'extraPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: 'NullBool'
attribute:
- 'notnull'
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
throws:
- name: 'IllegalArgumentException'
description: Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.
- name: 'favicon'
description: |
Sets the value to use for the favicon.<br>
The following values are supported:
<ul>
<li>URL to a valid PNG file.</li>
<li>File name (with <code>.png</code> extension) matching a file saved in the favicons folder of AdvancedServerList.</li>
<li><code>${player uuid}</code> to display the avatar of the player.
</ul>
Set to an empty String or <code>null</code> to not alter the Favicon.
parameters:
- name: 'favicon'
description: 'The favicon to set.'
type: 'String'
attribute:
- 'nullable'
returns: 'This Builder after the Favicon has been set. Useful for chaining.'
- name: 'hidePlayersEnabled'
description: |
Sets whether the player count should be hidden or not.<br>
<br>
Set to <a href="../../../objects/nullbool#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
parameters:
- name: 'hidePlayersEnabled'
description: 'Whether the player count should be hidden or not.'
type: 'NullBool'
attribute:
- 'notnull'
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
- name: 'maxPlayersCount'
description: |
Sets the number of max players allowed to join this server.<br>
This option has no effect when <a href="#maxplayersenabled(nullbool)">maxPlayersEnabled</a> is set to <a href="../../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively <a href="#maxplayersenabled(nullbool)">disable max Players</a>.
parameters:
- name: 'maxPlayersCount'
description: 'The number of max players to set.'
type: 'Integer'
attribute:
- 'nullable'
returns: 'This Builder after the max player count has been set. Useful for chaining.'
- name: 'maxPlayersEnabled'
description: |
Sets whether the max players feature should be enabled.<br>
<br>
Set to <a href="../../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a> to not set this.<br>
<br>
An <code>IllegalArgumentException</code> may be thrown by the <code>CheckUtil</code> should maxPlayersEnabled be null.
parameters:
- name: 'maxPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: 'NullBool'
attribute:
- 'notnull'
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
- name: 'motd'
description: |
Sets a new MOTD to use.<br>
<br>
Set to an empty list to not change the MOTD.<br>
Only the first two entries of the list will be considered and any additional ones discarded.
returns: 'This Builder after the motd has been set. Useful for chaining.'
Only the first two entries of the list will be considered and any additional ones discarded.<br>
<br>
An <code>IllegalArgumentException</code> may be thrown by the <code>CheckUtil</code> should the provided motd list be null.
parameters:
- name: 'motd'
description: 'The MOTD to use.'
type: 'List<String>'
attributes:
- notnull
attribute:
- 'notnull'
returns: 'This Builder after the motd has been set. Useful for chaining.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setPlayers'
description: |
Sets the players (lines) to use for the hover.<br>
<br>
Set to an empty list to not change the hover text.
returns: 'This Builder after the players have been set. Useful for chaining.'
parameters:
- name: 'players'
description: 'The lines to set for the hover.'
type: 'List<String>'
attributes:
- notnull
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setPlayerCountText'
- name: 'playerCountText'
description: |
Sets the text to override the player count with.<br>
<br>
Set to an empty String or <code>null</code> to not alter the player count text.
returns: 'This Builder after the player count text has been set. Useful for chaining.'
parameters:
- name: 'playerCountText'
description: 'The text to show in the player count.'
type: String
attributes:
type: 'String'
attribute:
- 'nullable'
returns: 'This Builder after the player count text has been set. Useful for chaining.'
- name: 'players'
description: |
Sets the players (lines) to use for the hover.<br>
<br>
Set to an empty list to not change the hover text.
<br>
An <code>IllegalArgumentException</code> may be thrown by the <code>CheckUtil</code> should the provided okayersmotd list be null.
parameters:
- name: 'players'
description: 'The lines to set for the hover.'
type: 'List<String>'
attribute:
- 'notnull'
returns: 'This Builder after the players have been set. Useful for chaining.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
- name: 'build'
description: 'Creates a new <a href="./.."><code>ProfileEntry</code> instance</a> with the values set in this Builder.'
returns: 'New <a href="./.."><code>ProfileEntry</code> instance</a>.'
type:
name: 'ProfileEntry'
type: 'object'
link: './..'
#
# Deprecated stuff
#
- name: 'setExtraPlayerCount'
description: |
Sets the number of players to add to the online players to use as the new max players value.<br>
This option has no effect when <a href="../#extraplayersenabled()"><code>extraPlayersEnabled</code></a> is set to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively, set <a href="#setextraplayersenabled(nullbool)"><code>setExtraPlayersEnabled(NullBool)</code></a> to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a>.
returns: 'This Builder after the extra player count has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersCount'
description: 'The number of extra players to add.'
type: Integer
attribute:
- nullable
deprecated: 'Typo in the name. Use <a href="#setextraplayerscount(integer)">setExtraPlayersCount(Integer)</a> instead.'
type:
name: 'Builder'
type: 'object'
- name: 'setExtraPlayersCount'
description: |
Sets the number of players to add to the online players to use as the new max players value.<br>
This option has no effect when <a href="../#extraplayersenabled()"><code>extraPlayersEnabled</code></a> is set to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively, set <a href="#setextraplayersenabled(nullbool)"><code>setExtraPlayersEnabled(NullBool)</code></a> to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a>.
returns: 'This Builder after the extra player count has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersCount'
description: 'The number of extra players to add.'
type: Integer
attribute:
- nullable
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#extraplayerscount(integer)">extraPlayersCount(Integer)</a> instead.'
type:
name: 'Builder'
type: 'object'
- name: 'setExtraPlayersEnabled'
description: |
Sets whether the extra players feature should be enabled or not.<br>
<br>
Set to <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: NullBool
attribute:
- notnull
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#extraplayersenabled(nullbool)">extraPlayersEnabled(NullBool)</a> instead.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
@@ -71,8 +225,9 @@ methods:
- name: 'favicon'
description: 'The favicon to set'
type: String
attributes:
attribute:
- nullable
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#favicon(string)">favicon(String)</a> instead.'
type:
name: 'Builder'
type: 'object'
@@ -86,83 +241,15 @@ methods:
- name: 'hidePlayersEnabled'
description: 'Whether the player count should be hidden or not.'
type: NullBool
attributes:
attribute:
- notnull
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#hideplayersenabled(nullbool)">hidePlayersEnabled(NullBool)</a> instead.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setExtraPlayersEnabled'
description: |
Sets whether the extra players feature should be enabled or not.<br>
<br>
Set to <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: NullBool
attributes:
- notnull
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setMaxPlayersEnabled'
description: |
Sets whether the max players feature should be enabled.<br>
<br>
Set to <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
parameters:
- name: 'maxPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: NullBool
attributes:
- notnull
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setExtraPlayerCount'
description: |
Sets the number of players to add to the online players to use as the new max players value.<br>
This option has no effect when <a href="../#extraplayersenabled()"><code>extraPlayersEnabled</code></a> is set to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively, set <a href="#setextraplayersenabled(nullbool)"><code>setExtraPlayersEnabled(NullBool)</code></a> to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a>.
returns: 'This Builder after the extra player count has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersCount'
description: 'The number of extra players to add.'
type: Integer
attributes:
- nullable
deprecated: 'Typo in the name. Use <a href="#setextraplayerscount(integer)">setExtraPlayersCount(Integer)</a> instead.'
type:
name: 'Builder'
type: 'object'
- name: 'setExtraPlayersCount'
description: |
Sets the number of players to add to the online players to use as the new max players value.<br>
This option has no effect when <a href="../#extraplayersenabled()"><code>extraPlayersEnabled</code></a> is set to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a> or <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a>.<br>
<br>
Set this to <code>null</code> to not alter the max player count. Alternatively, set <a href="#setextraplayersenabled(nullbool)"><code>setExtraPlayersEnabled(NullBool)</code></a> to <a href="../../objects/nullbool/#false"><code>NullBool.FALSE</code></a>.
returns: 'This Builder after the extra player count has been set. Useful for chaining.'
parameters:
- name: 'extraPlayersCount'
description: 'The number of extra players to add.'
type: Integer
attributes:
- nullable
type:
name: 'Builder'
type: 'object'
- name: 'setMaxPlayersCount'
description: |
Sets the number of max players allowed to join this server.<br>
@@ -174,18 +261,86 @@ methods:
- name: 'maxPlayersCount'
description: 'The number of max players to set.'
type: Integer
attributes:
attribute:
- nullable
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#maxplayerscount(integer)">maxPlayersCount(Integer)</a> instead.'
type:
name: 'Builder'
type: 'object'
- name: 'build'
description: 'Creates a new <a href="./.."><code>ProfileEntry</code> instance</a> with the values set in this Builder.'
returns: 'New <a href="./.."><code>ProfileEntry</code> instance</a>.'
- name: 'setMaxPlayersEnabled'
description: |
Sets whether the max players feature should be enabled.<br>
<br>
Set to <a href="../../objects/nullbool/#not_set"><code>NullBool.NOT_SET</code></a> to not set this.
returns: 'This Builder after the NullBool has been set. Useful for chaining.'
parameters:
- name: 'maxPlayersEnabled'
description: 'Whether the extra players feature should be enabled or not.'
type: NullBool
attribute:
- notnull
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#maxplayersenabled(nullbool)">maxPlayersEnabled(NullBool)</a> instead.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'ProfileEntry'
name: 'Builder'
type: 'object'
- name: 'setMotd'
description: |
Sets a new MOTD to use.<br>
<br>
Set to an empty list to not change the MOTD.<br>
Only the first two entries of the list will be considered and any additional ones discarded.
returns: 'This Builder after the motd has been set. Useful for chaining.'
parameters:
- name: 'motd'
description: 'The MOTD to use.'
type: 'List<String>'
attribute:
- notnull
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#motd(string)">motd(String)</a> instead.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
- name: 'setPlayerCountText'
description: |
Sets the text to override the player count with.<br>
<br>
Set to an empty String or <code>null</code> to not alter the player count text.
returns: 'This Builder after the player count text has been set. Useful for chaining.'
parameters:
- name: 'playerCountText'
description: 'The text to show in the player count.'
type: String
attribute:
- nullable
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#playercounttext(string)">playerCountText(String)</a> instead.'
type:
name: 'Builder'
type: 'object'
- name: 'setPlayers'
description: |
Sets the players (lines) to use for the hover.<br>
<br>
Set to an empty list to not change the hover text.
returns: 'This Builder after the players have been set. Useful for chaining.'
parameters:
- name: 'players'
description: 'The lines to set for the hover.'
type: 'List<String>'
attribute:
- notnull
deprecated: 'Method renamed to fit <a href="..">ProfileEntry</a> record more closely. Use <a href="#players(list<string>)">players(List&lt;String&gt;)</a> instead.'
throws:
- name: 'IllegalArgumentException'
description: 'Thrown by the <code>CheckUtil</code> in case <code>null</code> has been provided as parameter.'
type:
name: 'Builder'
type: 'object'
link: './..'
---
# <api__class></api__class> Builder
+2 -2
View File
@@ -1,10 +1,10 @@
---
template: redirect.html
location: https://github.com/Andre601/asl-api
location: https://codeberg.org/Andre601/asl-api
title: Source Code
icon: octicons/mark-github-16
icon: simple/codeberg
---
<!-- Comment to trigger proper build -->
+6 -6
View File
@@ -1,5 +1,5 @@
document$.subscribe(async () => {
const url = 'https://codeberg-stats-proxy.vercel.app/repo'
const url = 'https://codeberg-stats-proxy.vercel.app'
const repo_stats = document.querySelector('[data-md-component="source"] .md-source__repository');
function loadCodebergInfo(data) {
@@ -31,7 +31,7 @@ document$.subscribe(async () => {
const versionToken = '{apiVersion}';
const codeBlocks = document.querySelectorAll('.md-content pre code');
for(const codeBlock of codeBlocks) {
codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(versionToken, 'g'), version);
codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(versionToken, 'g'), version.substring(1));
}
}
@@ -45,10 +45,10 @@ document$.subscribe(async () => {
}
async function fetchApiInfo() {
const tag = await fetch("https://api.github.com/repos/Andre601/asl-api/releases/latest").then(_ => _.json());
const tag = await fetch(`${url}/api/latest-release`).then(_ => _.json());
const data = {
"version": tag.tag_name
"version": tag.name
};
__md_set("__api_tag", data, sessionStorage);
@@ -57,8 +57,8 @@ document$.subscribe(async () => {
async function fetchInfo() {
const [release, repo] = await Promise.all([
fetch(`${url}/latest-release`).then(_ => _.json()),
fetch(`${url}/stats`).then(_ => _.json()),
fetch(`${url}/repo/latest-release`).then(_ => _.json()),
fetch(`${url}/repo/stats`).then(_ => _.json()),
]);
const data = {
+23
View File
@@ -0,0 +1,23 @@
:root {
--admonition-icon--file: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M3 3a2 2 0 0 1 2-2h9.982a2 2 0 0 1 1.414.586l4.018 4.018A2 2 0 0 1 21 7.018V21a2 2 0 0 1-2 2H4.75a.75.75 0 0 1 0-1.5H19a.5.5 0 0 0 .5-.5V8.5h-4a2 2 0 0 1-2-2v-4H5a.5.5 0 0 0-.5.5v6.25a.75.75 0 0 1-1.5 0Zm12-.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 0-.146-.336l-4.018-4.018A.5.5 0 0 0 15 2.5Z"></path><path d="M4.53 12.24a.75.75 0 0 1-.039 1.06l-2.639 2.45 2.64 2.45a.75.75 0 1 1-1.022 1.1l-3.23-3a.75.75 0 0 1 0-1.1l3.23-3a.75.75 0 0 1 1.06.04Zm3.979 1.06a.75.75 0 1 1 1.02-1.1l3.231 3a.75.75 0 0 1 0 1.1l-3.23 3a.75.75 0 1 1-1.021-1.1l2.639-2.45-2.64-2.45Z"></path></svg>');
--admonition-color-fg--file: #00c853;
--admonition-color-bg--file: #00c8531a;
}
.md-typeset .admonition.file,
.md-typeset details.file {
border-color: var(--admonition-color-fg--file);
}
.md-typeset .file > .admonition-title,
.md-typeset .file > summary {
background-color: var(--admonition-color-bg--file);
}
.md-typeset .file > .admonition-title::before,
.md-typeset .file > summary::before {
background-color: var(--admonition-color-fg--file);
-webkit-mask-image: var(--admonition-icon--file);
mask-image: var(--admonition-icon--file);
}
+61 -23
View File
@@ -5,7 +5,7 @@ icon: octicons/milestone-24
# Getting Started
This page will explain how to set up AdvancedServerList and make it work for your server.
It tries to be an easy to understand as possible. But if you still have problems, consider joining the [Discord Server](https://discord.gg/6dazXp6) for help.
It tries to be as easy to understand as possible. But if you still have problems, consider joining the [Discord Server](https://discord.gg/6dazXp6) for help.
## 1. Download the plugin { #download-the-plugin }
@@ -53,46 +53,67 @@ The plugin also supports these additional plugins. They are all optional.
<div class="grid cards" markdown>
- [**PlaceholderAPI**][placeholderapi]
----
Supported on:
AdvancedServerList supports the use of placeholder from PlaceholderAPI in all its text options, excluding the `condition` option.
- :fontawesome-solid-paper-plane: Paper
----
**Supported on:**
:fontawesome-solid-paper-plane: Paper
- [**ViaVersion**][viaversion]
----
Supported on:
When installed will AdvancedServerList use ViaVersion to resolve the protocol version of a player for its PlaceholderAPI placeholders.
- :fontawesome-solid-paper-plane: Paper
----
**Supported on:**
:fontawesome-solid-paper-plane: Paper
- [**PAPIProxyBridge**][papiproxybridge]
----
Supported on:
Allows AdvancedServerList to parse placeholders from PlaceholderAPI while being used on a proxy.
- :simple-spigotmc: BungeeCord
- :fontawesome-solid-paper-plane: Velocity
----
**Supported on:**
:simple-spigotmc: BungeeCord, :fontawesome-solid-paper-plane: Velocity
- [**Maintenance**][maintenance]
----
Supported on:
AdvancedServerList will disable any modification of the server list entry should Maintenance mode be enabled.
- :fontawesome-solid-paper-plane: Paper
- :simple-spigotmc: BungeeCord
- :fontawesome-solid-paper-plane: Velocity
----
**Supported on:**
:fontawesome-solid-paper-plane: Paper, :simple-spigotmc: BungeeCord, :fontawesome-solid-paper-plane: Velocity
- [**BanPlugins Addon**][addon]
----
Official Add-on for AdvancedServerList that adds placeholders for different Ban/Punishment plugins such as AdvancedBan and LibertyBans.
----
**Supported on:**
:fontawesome-solid-paper-plane: Paper, :simple-spigotmc: BungeeCord, :fontawesome-solid-paper-plane: Velocity
</div>
[placeholderapi]: https://hangar.papermc.io/HelpChat/PlaceholderAPI
[viaversion]: https://hangar.papermc.io/ViaVersion/ViaVersion
[papiproxybridge]: https://hangar.papermc.io/William278/PAPIProxyBridge
[maintenance]: https://hangar.papermc.io/kennytv/Maintenance
[addon]: ../addons/banplugins.md
## 2. Installation { #installation }
@@ -130,6 +151,8 @@ The profiles folder is home of the server list profile files which allow you to
On first creation will the folder have a `default.yml` file. This file contains all the options available to use alongside comments to try and help you in using it properly.
/// details | default.yml content
type: file
```yaml
#
# Set the priority of this profile.
@@ -310,12 +333,15 @@ These functions include, but aren't limited to:
- Disabling/Enabling caching of players.
- Disabling/Enabling checking for updates.
- Disabling/Enabling debug mode.
- Setting how long favicons should be cached for.
- The config version used for migration. Don't touch this, or it may reset your config.
Similar to the default.yml is this file containing comments to try and explain the settings in questions.
Do note that if the config gets migrated from an older version, that the comments will be discarded in the process, unfortunately.
/// details | default config.yml content
type: file
```yaml
#
# Used for when AdvancedServerList doesn't have a cached player to use for player placeholders.
@@ -361,13 +387,21 @@ checkUpdates: true
#
debug: false
#
# Sets the time in minutes for favicons to be cached.
# The number cannot be less than 1.
#
# Defaults to 1 if not set.
#
faviconCacheTime: 1
#
# DO NOT EDIT!
#
# This is used internally to determine if the config needs to be migrated.
# Changing or even removing this option could result in your config being broken.
#
config-version: 2
config-version: 4
```
///
@@ -375,18 +409,22 @@ config-version: 2
There are certain files and folders that get created when certain events happen:
- A `playercache.json` file will be created on plugin shutdown containing a list of IPs, UUIDs and Player names for every player that joined the server while AdvancedServerList was running.
This file allows to replace `${player name}` and `${player uuid}` with their name or UUID respectively, while they are not on the server, by using the IP they used to join with.
This file is not created nor updated when `disableCache` is set to `true` in the config.yml
- A `playercache.json` file will be created on plugin shutdown containing a collection of IPs, UUIDs and Player names for every player that joined the server while AdvancedServerList was running.
This file is used to identify a player through their last used IP, to replace placeholders such as `${player name}` or `${player uuid}` with their respective values using the cached data.
This file is not created, used nor updated when `disableCache` is set to `true` in the config.yml
- A `backups` folder containing old config.yml files.
This folder is created when AdvancedServerList migrates your old config to a new version. This allows you to transfer settings over in case the migration didn't work properly.
This folder is created when AdvancedServerList migrates your old config to a new version. This allows you to transfer settings over in case the migration didn't work properly.
Each backup will have the name pattern `config-<date>.yml` with `<date>` being the date and time of when this file has been created.
## 3. Creating your first profile { #creating-your-first-profile }
Creating your first profile is relatively simple.
To start, open the `default.yml` file located inside the `profiles` folder using a file editor of your choice (VSCode or Notepad++ are recommended). It should contain all the available options for a server list profile.
Next can you edit the options available to whatever you like. All text options (Except [condition](../profiles/index.md#condition)) support [MiniMessage formatting](../profiles/formatting.md).
It's best to open the `default.yml` file located inside `profiles` with the file editor of your choice ([:simple-vscodium: VSCodeium](https://vscodium.com/) or [:simple-notepadplusplus: Notepad++](https://notepad-plus-plus.org/) are recommended).
This file should contain all available options that you can set and alter.
Edit the options to whatever you like. All text-based options, except [`condition`](../profiles/index.md#condition), support [MiniMessage formatting](../profiles/formatting.md).
The [`motd`](../profiles/index.md#motd) option also supports Hexadecimal colors, assuming the server/proxy runs at least MC 1.16.
If you're unsure how a specific option should look like, head over to the [Profiles page](../profiles/index.md) for more information about the general structure.
All you need to know is, that a bare-bones server list profile requires a valid [priority](../profiles/index.md#priority) and at least one of the settings to be present.
@@ -402,7 +440,7 @@ motd:
### Additional profiles
To add additional profiles, create a new YAML file inside the `profiles` folder. The name doesn't matter, but it is recommended to keep it lowercase, use alphanumeric characters (`a-z, 0-9`), hyphens (`-`), underscores (`_`) and avoid spaces.
To add additional profiles, create a new YAML file inside the `profiles` folder. The name doesn't matter, but it is recommended to keep it lowercase, use alphanumeric characters (`a-z, 0-9`), hyphens (`-`), underscores (`_`) and avoid spaces. You should also name it after what it is for, to have it more easily organized.
Inside the file, add a priority and at least one setting, similar to the above shown example.
This would already be enough to have a valid profile, but depending on the priority and file name may the file not be used, or used over other profiles.
@@ -411,7 +449,7 @@ If you want to only show this file under specific situations can you use the [`c
The condition option would have a single String containing one or muliple [Expressions](../profiles/expressions.md). Only if the condition would return true, would the profile be displayed, granted that it has a higher priority than any other valid file with a true condition output.
/// info | Note
Profiles which do not have any conditions, or have an empty condition, will always considered to have a true condition, meaning that a profile with higher priority and no condition will be selected over a profile with lower priority and a condition, even if said condition returns true.
Profiles which do not have any conditions, or have an empty condition, will always be considered to have a true condition, meaning that a profile with higher priority and no condition will be selected over a profile with lower priority and a condition, even if said condition returns true.
///
Here is another example profile using conditions to show it when the player was banned on the server:
@@ -431,7 +469,7 @@ The [Examples page](../examples/index.md) contains more examples of different se
## 4. Loading profiles { #loading-profiles }
Once you've set up your server list profile(s) is it time to load it/them.
To do this, simply run `/asl reload` as player (Requires permission `advancedserverlist.admin` or `advancedserverlist.command.reload`) or through the Server/Proxy console.
To do this, simply run `/asl reload` as player (Requires permission `advancedserverlist.admin` or `advancedserverlist.command.reload`) or `asl reload` through the Server/Proxy console.
The plugin should then load any valid YAML file inside the `profiles` folder to then use.
+5 -5
View File
@@ -33,7 +33,7 @@ The following cases are considered literal values:
Any number is considered an expression, meaning the below examples are considered valid:
/// example | Examples
```
```shell
0
1000
-7
@@ -53,7 +53,7 @@ To avoid this is it very important to always surround Strings with single or dou
///
/// example | Examples
```
```shell
"Hello World!"
""
```
@@ -68,7 +68,7 @@ Strings `true` and `false` are treated as boolean literals.
Any [placeholder](placeholders.md) is a valid expression.
/// example | Examples
```
```shell
${player protocol}
${player name}
@@ -110,7 +110,7 @@ These additional binary operators can also be used to perform certain actions:
| `/` | Divides one number by another. Strings use their text length as number. |
/// example | Examples
```
```shell
${player name} != "Anonymous"
763 > ${player protocol} > 758
${player hasPlayedBefore} and ${player isBanned} == "false"
@@ -126,7 +126,7 @@ Parenthesis can be used to prevent ambiguities.
`!` can be used to negate boolean expressions.
```
```shell
!${player isWhitelisted}
```
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more