1
0
Fork 0
mirror of https://github.com/xHyroM/lighteco.git synced 2024-11-10 17:38:07 +01:00

feat!: better command abstraction (#4)

* feat: better command abstraction

* feat: OfflineUserArgument type

* feat: balance, balance other cmds in common & double, integer arg

* feat: command manager, better arguments abstraction

* feat: map args

* feat: some things

* feat(better command abstraction)!: switch to brigadier (#8)

* feat: switch to brigadier

* some updates

* feat: make suggestion provider work

* supress warnings

* feat: pay & set command

* feat: give & take command, better suggestions, permissions

* refactor: cleanup

* fix: dont register pay if currency is not payable

* fix: send commands only if you have perms

* make second test currency not payable

* feat: use command's description & name

* refactor: cleanup, rename bukkit to paper

* refactor: cleanup, rename bukkit to paper

* feat: add built-in info command

* ci: build paper, not bukkit

* refactor: better test organization

* refactor: better test organization

* feat: locks

* feat: finish locking

* feat: handle missing user

* refactor: move methods to CommandHelper

* refactor: change minimum api version

* feat: console support
This commit is contained in:
Jozef Steinhübl 2024-07-16 18:04:37 +02:00 committed by GitHub
parent 75a1e8274a
commit 23e73cb5da
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
68 changed files with 1367 additions and 817 deletions

View file

@ -12,8 +12,7 @@ jobs:
distribution: 'adopt'
- name: Build with Gradle
run: |
./gradlew shadowJar -p bukkittest
./gradlew shadowJar -p bukkit
./gradlew shadowJar -p paper
./gradlew shadowJar -p currency-money
- uses: actions/upload-artifact@v3
with:

1
.gitignore vendored
View file

@ -7,6 +7,7 @@
### ForgeGradle ###
# Minecraft client/server files
run/
runServer/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider

View file

@ -11,7 +11,7 @@ public interface Platform {
@NonNull Type getType();
enum Type {
BUKKIT("Bukkit"),
PAPER("Paper"),
SPONGE("Sponge"),
VELOCITY("Velocity"),
BUNGEECORD("BungeeCord");
@ -27,7 +27,7 @@ public interface Platform {
}
public boolean isLocal() {
return this == BUKKIT || this == SPONGE;
return this == PAPER || this == SPONGE;
}
public boolean isProxy() {

View file

@ -28,6 +28,7 @@ subprojects {
repositories {
mavenCentral()
maven("https://storehouse.okaeri.eu/repository/maven-public/")
maven("https://libraries.minecraft.net")
}
}

View file

@ -4,7 +4,12 @@ plugins {
}
java {
// toolchain.languageVersion.set(JavaLanguageVersion.of(17))
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_17
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
withSourcesJar()
}
@ -13,6 +18,7 @@ tasks {
filesMatching(listOf("plugin.yml")) {
expand(
"name" to project.name,
"coreName" to "LightEco",
"version" to project.version,
"description" to project.description,
"author" to "xHyroM"

View file

@ -1,59 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.OfflinePlayerArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.xhyrom.lighteco.bukkit.chat.BukkitCommandSender;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import lombok.RequiredArgsConstructor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
@RequiredArgsConstructor
public class BalanceCommand implements Command {
private final BukkitCommandManager manager;
private final String name;
private final Currency currency;
private final String permissionBase;
@Override
public CommandAPICommand[] multipleBuild() {
return new CommandAPICommand[]{
new CommandAPICommand(name)
.withPermission(permissionBase + "balance.others")
.withArguments(new OfflinePlayerArgument("target"))
.executes((sender, args) -> {
this.handleBalance(sender, args, currency);
}),
new CommandAPICommand(name)
.withPermission(permissionBase + "balance")
.executesPlayer((sender, args) -> {
this.handleBalance(sender, args, currency);
})
};
}
public void handleBalance(CommandSender originalSender, CommandArguments args, Currency currency) {
BukkitCommandSender sender = new BukkitCommandSender(originalSender, this.manager.audienceFactory);
OfflinePlayer target = (OfflinePlayer) args.get("target");
if (target == null) {
this.manager.onBalance(sender, currency);
return;
}
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAccept(result -> {
String username = result.getUsername() == null ?
target.getName() != null
? target.getName()
: args.getRaw("target")
: result.getUsername();
result.setUsername(username);
this.manager.onBalance(sender, currency, result);
});
}
}

View file

@ -1,13 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
public interface Command {
default CommandAPICommand build() {
return null;
}
default CommandAPICommand[] multipleBuild() {
return new CommandAPICommand[0];
}
}

View file

@ -1,54 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.DoubleArgument;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.OfflinePlayerArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.xhyrom.lighteco.bukkit.chat.BukkitCommandSender;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import lombok.RequiredArgsConstructor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.math.BigDecimal;
@RequiredArgsConstructor
public class GiveCommand implements Command {
private final BukkitCommandManager manager;
private final Currency currency;
private final String permissionBase;
@Override
public CommandAPICommand build() {
return new CommandAPICommand("give")
.withPermission(permissionBase + "give")
.withArguments(
new OfflinePlayerArgument("target"),
currency.getProxy().fractionalDigits() > 0
? new DoubleArgument("amount", 1)
: new IntegerArgument("amount", 1)
)
.executes((sender, args) -> {
this.handleGive(sender, args, currency);
});
}
private void handleGive(CommandSender originalSender, CommandArguments args, Currency currency) {
BukkitCommandSender sender = new BukkitCommandSender(originalSender, this.manager.audienceFactory);
OfflinePlayer target = (OfflinePlayer) args.get("target");
BigDecimal amount = BigDecimal.valueOf(Double.parseDouble(args.getRaw("amount")));
if (!this.manager.canUse(sender, currency)) return;
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAccept(result -> {
String name = target.getName() != null ? target.getName() : args.getRaw("target");
result.setUsername(name);
this.manager.onGive(sender, currency, result, amount);
});
}
}

View file

@ -1,57 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.DoubleArgument;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.OfflinePlayerArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.xhyrom.lighteco.bukkit.chat.BukkitCommandSender;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import lombok.RequiredArgsConstructor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.math.BigDecimal;
@RequiredArgsConstructor
public class PayCommand implements Command {
private final BukkitCommandManager manager;
private final Currency currency;
private final String permissionBase;
@Override
public CommandAPICommand build() {
return new CommandAPICommand("pay")
.withPermission(permissionBase + "pay")
.withArguments(
new OfflinePlayerArgument("target"),
currency.getProxy().fractionalDigits() > 0
? new DoubleArgument("amount", 1)
: new IntegerArgument("amount", 1)
)
.executesPlayer((sender, args) -> {
this.handlePay(sender, args, currency);
});
}
private void handlePay(CommandSender originalSender, CommandArguments args, Currency currency) {
BukkitCommandSender sender = new BukkitCommandSender(originalSender, this.manager.audienceFactory);
OfflinePlayer target = (OfflinePlayer) args.get("target");
BigDecimal amount = BigDecimal.valueOf(Double.parseDouble(args.getRaw("amount")));
if (!this.manager.canUse(sender, currency)) return;
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAccept(result -> {
String username = result.getUsername() == null ?
target.getName() != null
? target.getName()
: args.getRaw("target")
: result.getUsername();
result.setUsername(username);
this.manager.onPay(sender, currency, result, amount);
});
}
}

View file

@ -1,54 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.DoubleArgument;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.OfflinePlayerArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.xhyrom.lighteco.bukkit.chat.BukkitCommandSender;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import lombok.RequiredArgsConstructor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.math.BigDecimal;
@RequiredArgsConstructor
public class SetCommand implements Command {
private final BukkitCommandManager manager;
private final Currency currency;
private final String permissionBase;
@Override
public CommandAPICommand build() {
return new CommandAPICommand("set")
.withPermission(permissionBase + "set")
.withArguments(
new OfflinePlayerArgument("target"),
currency.getProxy().fractionalDigits() > 0
? new DoubleArgument("amount", 0)
: new IntegerArgument("amount", 0)
)
.executes((sender, args) -> {
this.handleSet(sender, args, currency);
});
}
private void handleSet(CommandSender originalSender, CommandArguments args, Currency currency) {
BukkitCommandSender sender = new BukkitCommandSender(originalSender, this.manager.audienceFactory);
OfflinePlayer target = (OfflinePlayer) args.get("target");
BigDecimal amount = BigDecimal.valueOf(Double.parseDouble(args.getRaw("amount")));
if (!this.manager.canUse(sender, currency)) return;
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAccept(result -> {
String name = target.getName() != null ? target.getName() : args.getRaw("target");
result.setUsername(name);
this.manager.onSet(sender, currency, result, amount);
});
}
}

View file

@ -1,54 +0,0 @@
package dev.xhyrom.lighteco.bukkit.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.DoubleArgument;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.OfflinePlayerArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.xhyrom.lighteco.bukkit.chat.BukkitCommandSender;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import lombok.RequiredArgsConstructor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.math.BigDecimal;
@RequiredArgsConstructor
public class TakeCommand implements Command {
private final BukkitCommandManager manager;
private final Currency currency;
private final String permissionBase;
@Override
public CommandAPICommand build() {
return new CommandAPICommand("take")
.withPermission(permissionBase + "take")
.withArguments(
new OfflinePlayerArgument("target"),
currency.getProxy().fractionalDigits() > 0
? new DoubleArgument("amount", 1)
: new IntegerArgument("amount", 1)
)
.executes((sender, args) -> {
this.handleTake(sender, args, currency);
});
}
private void handleTake(CommandSender originalSender, CommandArguments args, Currency currency) {
BukkitCommandSender sender = new BukkitCommandSender(originalSender, this.manager.audienceFactory);
OfflinePlayer target = (OfflinePlayer) args.get("target");
BigDecimal amount = BigDecimal.valueOf(Double.parseDouble(args.getRaw("amount")));
if (!this.manager.canUse(sender, currency)) return;
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAccept(result -> {
String name = target.getName() != null ? target.getName() : args.getRaw("target");
result.setUsername(name);
this.manager.onTake(sender, currency, result, amount);
});
}
}

View file

@ -1,77 +0,0 @@
package dev.xhyrom.lighteco.bukkit.manager;
import dev.jorel.commandapi.CommandAPICommand;
import dev.xhyrom.lighteco.bukkit.commands.*;
import dev.xhyrom.lighteco.common.manager.command.AbstractCommandManager;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
public class BukkitCommandManager extends AbstractCommandManager {
public final BukkitAudiences audienceFactory;
public BukkitCommandManager(LightEcoPlugin plugin) {
super(plugin);
this.audienceFactory = BukkitAudiences.create((JavaPlugin) this.plugin.getBootstrap().getLoader());
}
@Override
public void registerCurrencyCommand(@NonNull Currency currency) {
registerCommands(currency.getIdentifier(), currency);
for (String alias : currency.getIdentifierAliases()) {
registerCommands(alias, currency);
}
}
@Override
public void registerCurrencyCommand(@NonNull Currency currency, boolean main) {
if (!main) {
registerCurrencyCommand(currency);
return;
}
String permissionBase = "lighteco.currency." + currency.getIdentifier() + ".command.";
// Register main command
registerCurrencyCommand(currency);
// Expose pay as main command
if (currency.isPayable())
new PayCommand(this, currency, permissionBase).build().register();
// Expose balance as main command
for (CommandAPICommand cmd : new BalanceCommand(
this,
"balance",
currency,
permissionBase
).multipleBuild()) {
cmd.register();
}
}
private void registerCommands(@NonNull String name, @NonNull Currency currency) {
String permissionBase = "lighteco.currency." + currency.getIdentifier() + ".command.";
BalanceCommand balanceCommand = new BalanceCommand(this, "balance", currency, permissionBase);
CommandAPICommand cmd = new CommandAPICommand(name)
.withSubcommand(new SetCommand(this, currency, permissionBase).build())
.withSubcommand(new GiveCommand(this, currency, permissionBase).build())
.withSubcommand(new TakeCommand(this, currency, permissionBase).build())
.withSubcommands(balanceCommand.multipleBuild())
// We want balance to be the default command
.executesPlayer((sender, args) -> {
balanceCommand.handleBalance(sender, args, currency);
});
if (currency.isPayable())
cmd = cmd.withSubcommand(new PayCommand(this, currency, permissionBase).build());
cmd.register();
}
}

44
bukkittest/.gitignore vendored
View file

@ -1,44 +0,0 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
runServer/

View file

@ -19,6 +19,8 @@ dependencies {
implementation("eu.okaeri:okaeri-configs-yaml-snakeyaml:5.0.0-beta.5")
implementation("eu.okaeri:okaeri-configs-validator-okaeri:5.0.0-beta.5")
compileOnly("com.mojang:brigadier:1.0.18")
compileOnly("com.zaxxer:HikariCP:5.0.1")
compileOnly("redis.clients:jedis:5.1.0")

View file

@ -5,8 +5,8 @@ import dev.xhyrom.lighteco.api.model.currency.Currency;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ApiCommandManager extends ApiAbstractManager<dev.xhyrom.lighteco.common.manager.command.CommandManager> implements CommandManager {
public ApiCommandManager(LightEcoPlugin plugin, dev.xhyrom.lighteco.common.manager.command.CommandManager handle) {
public class ApiCommandManager extends ApiAbstractManager<dev.xhyrom.lighteco.common.command.CommandManager> implements CommandManager {
public ApiCommandManager(LightEcoPlugin plugin, dev.xhyrom.lighteco.common.command.CommandManager handle) {
super(plugin, handle);
}
@ -15,7 +15,7 @@ public class ApiCommandManager extends ApiAbstractManager<dev.xhyrom.lighteco.co
dev.xhyrom.lighteco.common.model.currency.Currency internal = this.plugin.getCurrencyManager()
.getIfLoaded(currency.getIdentifier());
this.handle.registerCurrencyCommand(internal);
this.handle.register(internal, false);
}
@Override
@ -23,6 +23,6 @@ public class ApiCommandManager extends ApiAbstractManager<dev.xhyrom.lighteco.co
dev.xhyrom.lighteco.common.model.currency.Currency internal = this.plugin.getCurrencyManager()
.getIfLoaded(currency.getIdentifier());
this.handle.registerCurrencyCommand(internal, main);
this.handle.register(internal, main);
}
}

View file

@ -0,0 +1,55 @@
package dev.xhyrom.lighteco.common.command;
import com.mojang.brigadier.context.CommandContext;
import dev.xhyrom.lighteco.common.command.argument.type.OfflineUserArgument;
import dev.xhyrom.lighteco.common.command.exception.LockedUserException;
import dev.xhyrom.lighteco.common.config.message.CurrencyMessageConfig;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import lombok.experimental.UtilityClass;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import java.util.Map;
@UtilityClass
public class CommandHelper {
public static User getUser(CommandContext<CommandSource> context) {
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
User target = null;
try {
target = OfflineUserArgument.getOfflineUser(context, "target");
} catch (LockedUserException e) {
sender.sendMessage(MiniMessage.miniMessage().deserialize(
plugin.getConfig().messages.wait
));
}
if (target == null || target.getUsername() == null) {
String userName = context.getArgument("target", String.class);
sender.sendMessage(MiniMessage.miniMessage().deserialize(
plugin.getConfig().messages.userNotFound,
Placeholder.parsed("username", userName)
));
return null;
}
return target;
}
public static CurrencyMessageConfig getCurrencyMessageConfig(LightEcoPlugin plugin, Currency currency) {
Map<String, CurrencyMessageConfig> config = plugin.getConfig().messages.currency;
CurrencyMessageConfig currencyMessageConfig = config.get(currency.getIdentifier());
if (currencyMessageConfig == null) {
return config.get("default");
}
return currencyMessageConfig;
}
}

View file

@ -0,0 +1,130 @@
package dev.xhyrom.lighteco.common.command;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.commands.BalanceCommand;
import dev.xhyrom.lighteco.common.commands.CurrencyParentCommand;
import dev.xhyrom.lighteco.common.commands.InfoCommand;
import dev.xhyrom.lighteco.common.commands.PayCommand;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import lombok.Getter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.util.*;
import java.util.concurrent.*;
public class CommandManager {
protected final LightEcoPlugin plugin;
private final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("lighteco-command-executor")
.build()
);
@Getter
private final CommandDispatcher<CommandSource> dispatcher = new CommandDispatcher<>();
@Getter
private final Set<UUID> locks = ConcurrentHashMap.newKeySet();
private final Map<UUID, UUID> locksMappings = new ConcurrentHashMap<>();
public CommandManager(LightEcoPlugin plugin) {
this.plugin = plugin;
}
// Register built-in commands
public void register() {
register(new InfoCommand());
}
public void register(Currency currency, boolean main) {
register(new CurrencyParentCommand(currency));
if (main) {
register(BalanceCommand.create(currency));
register(PayCommand.create(currency));
}
}
protected void register(Command command) {
dispatcher.getRoot().addChild(command.build());
}
public void execute(CommandSender sender, String name, String[] args) {
if (!sender.isConsole() && locks.contains(sender.getUniqueId())) {
sender.sendMessage(MiniMessage.miniMessage().deserialize(
this.plugin.getConfig().messages.wait
));
return;
}
final CommandSource source = new CommandSource(this.plugin, sender);
final ParseResults<CommandSource> parseResults = dispatcher.parse(
name + (args.length > 0 ? " " + String.join(" ", args) : ""),
source
);
if (!sender.isConsole())
locks.add(sender.getUniqueId());
CompletableFuture.runAsync(() -> {
try {
dispatcher.execute(parseResults);
} catch (CommandSyntaxException e) {
this.sendError(sender, name, e);
} finally {
if (!source.sender().isConsole()) {
this.plugin.getBootstrap().getLogger().debug("Removing lock for " + sender.getUsername());
UUID target = locksMappings.get(sender.getUniqueId());
if (target != null) {
locks.remove(target);
locksMappings.remove(sender.getUniqueId());
this.plugin.getBootstrap().getLogger().debug("Removing lock caused by " + sender.getUsername() + " for " + target);
}
locks.remove(sender.getUniqueId());
}
}
}, executor);
}
public void lockBySender(CommandSender sender, UUID target) {
locks.add(target);
locksMappings.put(sender.getUniqueId(), target);
}
private void sendError(CommandSender sender, String name, CommandSyntaxException e) {
sender.sendMessage(Component.text(e.getRawMessage().getString(), NamedTextColor.RED));
if (e.getInput() != null && e.getCursor() >= 0) {
int j = Math.min(e.getInput().length(), e.getCursor());
Component msg = Component.empty().color(NamedTextColor.GRAY).clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + name));
if (j > 10) {
msg = msg.append(Component.text("..."));
}
msg = msg.append(Component.text(e.getInput().substring(Math.max(0, j - 10), j)));
if (j < e.getInput().length()) {
Component component = Component.text(e.getInput().substring(j)).color(NamedTextColor.RED).decorate(TextDecoration.UNDERLINED);
msg = msg.append(component);
}
msg = msg.append(Component.translatable("command.context.here").color(NamedTextColor.RED).decorate(TextDecoration.ITALIC));
sender.sendMessage(msg);
}
}
}

View file

@ -0,0 +1,8 @@
package dev.xhyrom.lighteco.common.command;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
public record CommandSource(@NonNull LightEcoPlugin plugin, @NonNull CommandSender sender) {
}

View file

@ -0,0 +1,36 @@
package dev.xhyrom.lighteco.common.command.abstraction;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.common.command.CommandSource;
import lombok.Getter;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Getter
public abstract class Command {
@NonNull
protected final String name;
@NonNull
private final String description;
@NonNull
private final List<String> aliases = new ArrayList<>();
public Command(@NonNull String name, @NonNull String description, String... aliases) {
this.name = name;
this.description = description;
Collections.addAll(this.aliases, aliases);
}
public abstract CommandNode<CommandSource> build();
protected LiteralArgumentBuilder<CommandSource> builder() {
return LiteralArgumentBuilder.literal(name);
}
}

View file

@ -0,0 +1,43 @@
package dev.xhyrom.lighteco.common.command.argument.type;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.exception.LockedUserException;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import java.util.UUID;
public class OfflineUserArgument implements ArgumentType<String> {
private OfflineUserArgument() {}
public static User getOfflineUser(CommandContext<CommandSource> context, String name) throws LockedUserException {
String userName = context.getArgument(name, String.class);
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
UUID uniqueId = plugin.getBootstrap().lookupUniqueId(userName).orElse(null);
if (uniqueId == null) {
return null;
}
if (sender.getUniqueId() != uniqueId && plugin.getCommandManager().getLocks().contains(uniqueId)) {
throw new LockedUserException(uniqueId);
}
// Lock the user to prevent race conditions
if (!sender.isConsole())
plugin.getCommandManager().lockBySender(context.getSource().sender(), uniqueId);
return plugin.getUserManager().loadUser(uniqueId).join();
}
@Override
public String parse(StringReader reader) throws CommandSyntaxException {
return reader.readString();
}
}

View file

@ -0,0 +1,9 @@
package dev.xhyrom.lighteco.common.command.exception;
import java.util.UUID;
public class LockedUserException extends Exception {
public LockedUserException(UUID uniqueId) {
super("User with uuid " + uniqueId + " is currently locked thus cannot be modified");
}
}

View file

@ -0,0 +1,34 @@
package dev.xhyrom.lighteco.common.command.suggestion.type;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class OfflineUserSuggestionProvider implements SuggestionProvider<CommandSource> {
public static OfflineUserSuggestionProvider create() {
return new OfflineUserSuggestionProvider();
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSource> context, SuggestionsBuilder builder) {
LightEcoPlugin plugin = context.getSource().plugin();
String remaining = builder.getRemaining();
for (UUID uniqueId : plugin.getBootstrap().getOnlinePlayers()) {
User user = plugin.getUserManager().getIfLoaded(uniqueId);
if (user == null) continue;
builder.suggest(user.getUsername());
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,83 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.command.suggestion.type.OfflineUserSuggestionProvider;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.*;
public class BalanceCommand extends Command {
private final Currency currency;
public static BalanceCommand create(@NonNull Currency currency) {
return new BalanceCommand(currency);
}
public BalanceCommand(@NonNull Currency currency) {
super("balance", "Check your balance");
this.currency = currency;
}
@Override
public CommandNode<CommandSource> build() {
return builder()
.then(
RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.requires((source) -> source.sender().eligible("lighteco.currency."+currency.getIdentifier()+".command.balance.others"))
.executes(context -> {
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
final User target = getUser(context);
if (target == null)
return SINGLE_SUCCESS;
BigDecimal balance = target.getBalance(currency);
sender.sendMessage(
MiniMessage.miniMessage().deserialize(
getCurrencyMessageConfig(plugin, currency).balanceOthers,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("balance", balance.toPlainString())
)
);
return SINGLE_SUCCESS;
}))
.requires((source) -> source.sender().eligible("lighteco.currency."+currency.getIdentifier()+".command.balance"))
.executes(context -> {
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
User user = plugin.getUserManager().getIfLoaded(sender.getUniqueId());
BigDecimal balance = user.getBalance(currency);
sender.sendMessage(
MiniMessage.miniMessage().deserialize(
getCurrencyMessageConfig(plugin, currency).balance,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("balance", balance.toPlainString())
)
);
return SINGLE_SUCCESS;
})
.build();
}
}

View file

@ -0,0 +1,62 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.getCurrencyMessageConfig;
public class CurrencyParentCommand extends Command {
private final Currency currency;
public CurrencyParentCommand(@NonNull Currency currency) {
super(
currency.getIdentifier(),
currency.getIdentifier()
);
this.currency = currency;
}
@Override
public CommandNode<CommandSource> build() {
LiteralArgumentBuilder<CommandSource> builder = builder()
.then(BalanceCommand.create(currency).build())
.then(SetCommand.create(currency).build())
.then(GiveCommand.create(currency).build())
.then(TakeCommand.create(currency).build())
.executes(context -> {
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
User user = plugin.getUserManager().getIfLoaded(sender.getUniqueId());
BigDecimal balance = user.getBalance(currency);
sender.sendMessage(
MiniMessage.miniMessage().deserialize(
getCurrencyMessageConfig(plugin, currency).balance,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("balance", balance.toPlainString())
)
);
return SINGLE_SUCCESS;
});
if (currency.isPayable())
builder = builder.then(PayCommand.create(currency).build());
return builder.build();
}
}

View file

@ -0,0 +1,106 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.api.exception.CannotBeGreaterThan;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.command.suggestion.type.OfflineUserSuggestionProvider;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.*;
public class GiveCommand extends Command {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
private final Currency currency;
public static GiveCommand create(@NonNull Currency currency) {
return new GiveCommand(currency);
}
public GiveCommand(@NonNull Currency currency) {
super("give", "Give a player some money");
this.currency = currency;
}
private void execute(CommandContext<CommandSource> context) {
final LightEcoPlugin plugin = context.getSource().plugin();
final CommandSender sender = context.getSource().sender();
final User target = getUser(context);
if (target == null)
return;
BigDecimal amount = BigDecimal.valueOf(currency.fractionalDigits() > 0
? context.getArgument("amount", Double.class)
: context.getArgument("amount", Integer.class));
amount = amount.setScale(currency.fractionalDigits(), RoundingMode.DOWN);
try {
target.deposit(currency, amount);
} catch (CannotBeGreaterThan e) {
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).cannotBeGreaterThan,
Placeholder.parsed("max", plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).set,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString())
)
);
}
@Override
public CommandNode<CommandSource> build() {
if (currency.fractionalDigits() > 0) {
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.give"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Double>argument("amount", DoubleArgumentType.doubleArg(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.give"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.give"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Integer>argument("amount", IntegerArgumentType.integer(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.give"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
}

View file

@ -0,0 +1,36 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
public class InfoCommand extends Command {
public InfoCommand() {
super("lighteco", "LightEco information");
}
@Override
public CommandNode<CommandSource> build() {
return builder()
.requires(source -> source.sender().eligible("lighteco.command.info"))
.executes(context -> {
LightEcoPlugin plugin = context.getSource().plugin();
CommandSender sender = context.getSource().sender();
sender.sendMessage(MiniMessage.miniMessage().deserialize(
"<#fa5246><bold>LightEco</bold></#fa5246> <dark_gray>(<#d6766f>v<version><dark_gray>) <white>on <#d6766f><platform>",
Placeholder.parsed("version", plugin.getBootstrap().getVersion()),
Placeholder.parsed("platform", plugin.getPlatformType().getName())
));
return SINGLE_SUCCESS;
})
.build();
}
}

View file

@ -0,0 +1,150 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.api.exception.CannotBeGreaterThan;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.command.suggestion.type.OfflineUserSuggestionProvider;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.*;
public class PayCommand extends Command {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
private final Currency currency;
public static PayCommand create(@NonNull Currency currency) {
return new PayCommand(currency);
}
public PayCommand(@NonNull Currency currency) {
super("pay", "Pay a player");
this.currency = currency;
}
private void execute(CommandContext<CommandSource> context) {
final LightEcoPlugin plugin = context.getSource().plugin();
final CommandSender sender = context.getSource().sender();
final User target = getUser(context);
if (target == null)
return;
BigDecimal amount = BigDecimal.valueOf(currency.fractionalDigits() > 0
? context.getArgument("amount", Double.class)
: context.getArgument("amount", Integer.class));
amount = amount.setScale(currency.fractionalDigits(), RoundingMode.DOWN);
final User user = plugin.getUserManager().getIfLoaded(sender.getUniqueId());
if (user == null) {
return;
}
if (user.getBalance(this.currency).compareTo(amount) < 0) {
sender.sendMessage(
miniMessage.deserialize(getCurrencyMessageConfig(plugin, this.currency).notEnoughMoney)
);
return;
}
// calculate tax using Currency#calculateTax
BigDecimal tax = currency.getProxy().calculateTax(user.getProxy(), amount);
tax = tax.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
// subtract tax from amount
BigDecimal taxedAmount = amount.subtract(tax);
try {
target.deposit(currency, taxedAmount);
user.withdraw(currency, amount);
} catch (CannotBeGreaterThan e) {
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).cannotBeGreaterThan,
Placeholder.parsed("max", plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
String template = tax.compareTo(BigDecimal.ZERO) > 0
? getCurrencyMessageConfig(plugin, this.currency).payWithTax
: getCurrencyMessageConfig(plugin, this.currency).pay;
String templateReceived = tax.compareTo(BigDecimal.ZERO) > 0
? getCurrencyMessageConfig(plugin, this.currency).payReceivedWithTax
: getCurrencyMessageConfig(plugin, this.currency).payReceived;
sender.sendMessage(
miniMessage.deserialize(
template,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("taxed_amount", taxedAmount.toPlainString()),
Placeholder.parsed("sender_balance", user.getBalance(currency).toPlainString()),
Placeholder.parsed("receiver_balance", target.getBalance(currency).toPlainString())
)
);
target.sendMessage(
miniMessage.deserialize(
templateReceived,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("sender", user.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("taxed_amount", taxedAmount.toPlainString()),
Placeholder.parsed("sender_balance", user.getBalance(currency).toPlainString()),
Placeholder.parsed("receiver_balance", target.getBalance(currency).toPlainString())
)
);
}
@Override
public CommandNode<CommandSource> build() {
if (currency.fractionalDigits() > 0) {
return builder()
.requires((source) -> !source.sender().isConsole() && source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.pay"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Double>argument("amount", DoubleArgumentType.doubleArg(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.pay"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
return builder()
.requires((source) -> !source.sender().isConsole() && source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.pay"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Integer>argument("amount", IntegerArgumentType.integer(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.pay"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
}

View file

@ -0,0 +1,106 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.api.exception.CannotBeGreaterThan;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.command.suggestion.type.OfflineUserSuggestionProvider;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.*;
public class SetCommand extends Command {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
private final Currency currency;
public static SetCommand create(@NonNull Currency currency) {
return new SetCommand(currency);
}
public SetCommand(@NonNull Currency currency) {
super("set", "Set a player's balance");
this.currency = currency;
}
private void execute(CommandContext<CommandSource> context) {
final LightEcoPlugin plugin = context.getSource().plugin();
final CommandSender sender = context.getSource().sender();
final User target = getUser(context);
if (target == null)
return;
BigDecimal amount = BigDecimal.valueOf(currency.fractionalDigits() > 0
? context.getArgument("amount", Double.class)
: context.getArgument("amount", Integer.class));
amount = amount.setScale(currency.fractionalDigits(), RoundingMode.DOWN);
try {
target.setBalance(currency, amount);
} catch (CannotBeGreaterThan e) {
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).cannotBeGreaterThan,
Placeholder.parsed("max", plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).set,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString())
)
);
}
@Override
public CommandNode<CommandSource> build() {
if (currency.fractionalDigits() > 0) {
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.set"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Double>argument("amount", DoubleArgumentType.doubleArg(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.set"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.set"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Integer>argument("amount", IntegerArgumentType.integer(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.set"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
}

View file

@ -0,0 +1,106 @@
package dev.xhyrom.lighteco.common.commands;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.tree.CommandNode;
import dev.xhyrom.lighteco.api.exception.CannotBeGreaterThan;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.command.suggestion.type.OfflineUserSuggestionProvider;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static dev.xhyrom.lighteco.common.command.CommandHelper.*;
public class TakeCommand extends Command {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
private final Currency currency;
public static TakeCommand create(@NonNull Currency currency) {
return new TakeCommand(currency);
}
public TakeCommand(@NonNull Currency currency) {
super("take", "Take money from a player");
this.currency = currency;
}
private void execute(CommandContext<CommandSource> context) {
final LightEcoPlugin plugin = context.getSource().plugin();
final CommandSender sender = context.getSource().sender();
final User target = getUser(context);
if (target == null)
return;
BigDecimal amount = BigDecimal.valueOf(currency.fractionalDigits() > 0
? context.getArgument("amount", Double.class)
: context.getArgument("amount", Integer.class));
amount = amount.setScale(currency.fractionalDigits(), RoundingMode.DOWN);
try {
target.withdraw(currency, amount);
} catch (CannotBeGreaterThan e) {
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).cannotBeGreaterThan,
Placeholder.parsed("max", plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
getCurrencyMessageConfig(plugin, this.currency).set,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString())
)
);
}
@Override
public CommandNode<CommandSource> build() {
if (currency.fractionalDigits() > 0) {
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.take"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Double>argument("amount", DoubleArgumentType.doubleArg(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.take"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
return builder()
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.take"))
.then(RequiredArgumentBuilder.<CommandSource, String>argument("target", StringArgumentType.word())
.suggests(OfflineUserSuggestionProvider.create())
.then(RequiredArgumentBuilder.<CommandSource, Integer>argument("amount", IntegerArgumentType.integer(1))
.requires((source) -> source.sender().eligible("lighteco.currency." + currency.getIdentifier() + ".command.take"))
.executes(c -> {
execute(c);
return SINGLE_SUCCESS;
})))
.build();
}
}

View file

@ -17,7 +17,6 @@ public class CurrencyMessageConfig extends OkaeriConfig {
public String payReceived = "<currency> <dark_gray>| <gray>Received <gold><amount> <yellow>from <gold><sender>";
public String payReceivedWithTax = "<currency> <dark_gray>| <gray>Received <gold><amount> <yellow>from <gold><sender> <dark_gray>(<gold><taxed_amount> <yellow>after tax<dark_gray>)";
public String wait = "<red>Please wait a moment before using this command again.";
public String notEnoughMoney = "<red>You don't have enough money!";
public String cannotPaySelf = "<red>You cannot pay yourself!";
public String cannotBeGreaterThan = "<red>Amount cannot be greater than <gold><max>";

View file

@ -7,4 +7,7 @@ import java.util.Map;
public class MessageConfig extends OkaeriConfig {
public Map<String, CurrencyMessageConfig> currency = Collections.singletonMap("default", new CurrencyMessageConfig());
public String wait = "<red>Please wait a moment before using this command again.";
public String userNotFound = "<red>User <username> not found.";
}

View file

@ -1,275 +0,0 @@
package dev.xhyrom.lighteco.common.manager.command;
import dev.xhyrom.lighteco.api.exception.CannotBeGreaterThan;
import dev.xhyrom.lighteco.common.config.message.CurrencyMessageConfig;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
public abstract class AbstractCommandManager implements CommandManager {
public final LightEcoPlugin plugin;
private final MiniMessage miniMessage = MiniMessage.miniMessage();
private final Map<String, CurrencyMessageConfig> config;
private final ArrayList<UUID> mustWait = new ArrayList<>();
protected AbstractCommandManager(LightEcoPlugin plugin) {
this.plugin = plugin;
this.config = this.plugin.getConfig().messages.currency;
}
@Override
public boolean canUse(CommandSender sender, Currency currency) {
// Console doesn't need to wait
if (sender.getUniqueId() == null) return true;
if (mustWait.contains(sender.getUniqueId())) {
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).wait
)
);
return false;
}
return true;
}
private void addToMustWait(UUID ...uuids) {
for (UUID uuid : uuids) {
if (uuid != null)
mustWait.add(uuid);
}
}
private void removeFromMustWait(UUID ...uuids) {
for (UUID uuid : uuids) {
if (uuid != null)
mustWait.remove(uuid);
}
}
private CurrencyMessageConfig getConfig(Currency currency) {
CurrencyMessageConfig currencyMessageConfig = this.config.get(currency.getIdentifier());
if (currencyMessageConfig == null) {
return this.config.get("default");
}
return currencyMessageConfig;
}
@Override
public void onBalance(CommandSender sender, Currency currency) {
User user = this.plugin.getUserManager().getIfLoaded(sender.getUniqueId());
BigDecimal balance = user.getBalance(currency);
sender.sendMessage(
miniMessage.deserialize(
getConfig(currency).balance,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("balance", balance.toPlainString())
)
);
}
@Override
public void onBalance(CommandSender sender, Currency currency, User target) {
BigDecimal balance = target.getBalance(currency);
sender.sendMessage(
miniMessage.deserialize(
getConfig(currency).balanceOthers,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("balance", balance.toPlainString())
)
);
}
@Override
public void onSet(CommandSender sender, Currency currency, User target, BigDecimal amount) {
addToMustWait(sender.getUniqueId(), target.getUniqueId());
amount = amount.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
try {
target.setBalance(currency, amount);
} catch (CannotBeGreaterThan e) {
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).cannotBeGreaterThan,
Placeholder.parsed("max", this.plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).set,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString())
)
);
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
}
@Override
public void onGive(CommandSender sender, Currency currency, User target, BigDecimal amount) {
addToMustWait(sender.getUniqueId(), target.getUniqueId());
amount = amount.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
try {
target.deposit(currency, amount);
} catch (CannotBeGreaterThan e) {
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).cannotBeGreaterThan,
Placeholder.parsed("max", this.plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).give,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("balance", target.getBalance(currency).toPlainString())
)
);
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
}
@Override
public void onTake(CommandSender sender, Currency currency, User target, BigDecimal amount) {
addToMustWait(sender.getUniqueId(), target.getUniqueId());
amount = amount.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
try {
target.withdraw(currency, amount);
} catch (CannotBeGreaterThan e) {
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).cannotBeGreaterThan,
Placeholder.parsed("max", this.plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).take,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("balance", target.getBalance(currency).toPlainString())
)
);
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
}
@Override
public void onPay(CommandSender sender, Currency currency, User target, BigDecimal amount) {
if (sender.getUniqueId() != null && (sender.getUniqueId() == target.getUniqueId())) {
sender.sendMessage(
miniMessage.deserialize(this.getConfig(currency).cannotPaySelf)
);
return;
}
amount = amount.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
User user = this.plugin.getUserManager().getIfLoaded(sender.getUniqueId());
if (user.getBalance(currency).compareTo(amount) < 0) {
sender.sendMessage(
miniMessage.deserialize(this.getConfig(currency).notEnoughMoney)
);
return;
}
addToMustWait(sender.getUniqueId(), target.getUniqueId());
// calculate tax using Currency#calculateTax
BigDecimal tax = currency.getProxy().calculateTax(user.getProxy(), amount);
tax = tax.setScale(currency.getProxy().fractionalDigits(), RoundingMode.DOWN);
// subtract tax from amount
BigDecimal taxedAmount = amount.subtract(tax);
try {
target.deposit(currency, taxedAmount);
user.withdraw(currency, amount);
} catch (CannotBeGreaterThan e) {
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
sender.sendMessage(
miniMessage.deserialize(
this.getConfig(currency).cannotBeGreaterThan,
Placeholder.parsed("max", this.plugin.getConfig().maximumBalance.toPlainString())
)
);
return;
}
String template = tax.compareTo(BigDecimal.ZERO) > 0
? this.getConfig(currency).payWithTax
: this.getConfig(currency).pay;
String templateReceived = tax.compareTo(BigDecimal.ZERO) > 0
? this.getConfig(currency).payReceivedWithTax
: this.getConfig(currency).payReceived;
sender.sendMessage(
miniMessage.deserialize(
template,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("target", target.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("taxed_amount", taxedAmount.toPlainString()),
Placeholder.parsed("sender_balance", user.getBalance(currency).toPlainString()),
Placeholder.parsed("receiver_balance", target.getBalance(currency).toPlainString())
)
);
target.sendMessage(
miniMessage.deserialize(
templateReceived,
Placeholder.parsed("currency", currency.getIdentifier()),
Placeholder.parsed("sender", user.getUsername()),
Placeholder.parsed("amount", amount.toPlainString()),
Placeholder.parsed("taxed_amount", taxedAmount.toPlainString()),
Placeholder.parsed("sender_balance", user.getBalance(currency).toPlainString()),
Placeholder.parsed("receiver_balance", target.getBalance(currency).toPlainString())
)
);
removeFromMustWait(target.getUniqueId(), sender.getUniqueId());
}
}

View file

@ -1,23 +0,0 @@
package dev.xhyrom.lighteco.common.manager.command;
import dev.xhyrom.lighteco.common.model.chat.CommandSender;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal;
public interface CommandManager {
void registerCurrencyCommand(@NonNull Currency currency);
void registerCurrencyCommand(@NonNull Currency currency, boolean main);
boolean canUse(CommandSender sender, Currency currency);
void onBalance(CommandSender sender, Currency currency);
void onBalance(CommandSender sender, Currency currency, User target);
void onSet(CommandSender sender, Currency currency, User target, BigDecimal amount);
void onGive(CommandSender sender, Currency currency, User target, BigDecimal amount);
void onTake(CommandSender sender, Currency currency, User target, BigDecimal amount);
void onPay(CommandSender sender, Currency currency, User target, BigDecimal amount);
}

View file

@ -1,12 +1,18 @@
package dev.xhyrom.lighteco.common.model.chat;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public interface CommandSender {
String getUsername();
UUID getUniqueId();
@Nullable UUID getUniqueId();
boolean eligible(String permission);
void sendMessage(Component message);
default boolean isConsole() {
return getUniqueId() == null;
}
}

View file

@ -65,6 +65,9 @@ public abstract class AbstractLightEcoPlugin implements LightEcoPlugin {
// setup managers
this.setupManagers();
// register built-in commands
this.getCommandManager().register();
// register platform hooks
this.registerPlatformHooks();

View file

@ -2,9 +2,9 @@ package dev.xhyrom.lighteco.common.plugin;
import dev.xhyrom.lighteco.api.manager.ContextManager;
import dev.xhyrom.lighteco.api.platform.Platform;
import dev.xhyrom.lighteco.common.command.CommandManager;
import dev.xhyrom.lighteco.common.config.Config;
import dev.xhyrom.lighteco.common.dependencies.DependencyManager;
import dev.xhyrom.lighteco.common.manager.command.CommandManager;
import dev.xhyrom.lighteco.common.manager.currency.CurrencyManager;
import dev.xhyrom.lighteco.common.manager.user.UserManager;
import dev.xhyrom.lighteco.common.messaging.InternalMessagingService;

View file

@ -7,6 +7,7 @@ import net.kyori.adventure.audience.Audience;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface LightEcoBootstrap {
@ -14,8 +15,12 @@ public interface LightEcoBootstrap {
PluginLogger getLogger();
SchedulerAdapter getScheduler();
Path getDataDirectory();
String getVersion();
Optional<UUID> lookupUniqueId(String username);
boolean isPlayerOnline(UUID uniqueId);
List<UUID> getOnlinePlayers();
InputStream getResourceStream(String filename);
Audience getPlayerAudience(UUID uniqueId);
}

View file

@ -4,6 +4,9 @@ public interface PluginLogger {
void info(String message);
void info(String message, Object ...args);
void debug(String message);
void debug(String message, Object ...args);
void warn(String message);
void warn(String message, Object ...args);

View file

@ -1,23 +1,23 @@
package dev.xhyrom.lighteco.currency.money.bukkit;
package dev.xhyrom.lighteco.currency.money.paper;
import dev.xhyrom.lighteco.api.LightEco;
import dev.xhyrom.lighteco.api.LightEcoProvider;
import dev.xhyrom.lighteco.api.manager.CommandManager;
import dev.xhyrom.lighteco.api.manager.CurrencyManager;
import dev.xhyrom.lighteco.api.model.currency.Currency;
import dev.xhyrom.lighteco.currency.money.bukkit.hooks.vault.VaultFactory;
import dev.xhyrom.lighteco.currency.money.paper.hooks.vault.VaultFactory;
import dev.xhyrom.lighteco.currency.money.common.AbstractPlugin;
import dev.xhyrom.lighteco.currency.money.common.Plugin;
import dev.xhyrom.lighteco.currency.money.common.currency.MoneyCurrency;
import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
public class BukkitMCLoader extends JavaPlugin {
public class PaperMCLoader extends JavaPlugin {
private VaultFactory vaultFactory;
@Getter
private final Plugin plugin;
public BukkitMCLoader() {
public PaperMCLoader() {
this.plugin = new AbstractPlugin(this.getDataFolder().toPath());
}

View file

@ -1,4 +1,4 @@
package dev.xhyrom.lighteco.currency.money.bukkit.hooks.vault;
package dev.xhyrom.lighteco.currency.money.paper.hooks.vault;
import dev.xhyrom.lighteco.api.LightEco;
import dev.xhyrom.lighteco.api.LightEcoProvider;

View file

@ -1,16 +1,16 @@
package dev.xhyrom.lighteco.currency.money.bukkit.hooks.vault;
package dev.xhyrom.lighteco.currency.money.paper.hooks.vault;
import dev.xhyrom.lighteco.currency.money.bukkit.BukkitMCLoader;
import dev.xhyrom.lighteco.currency.money.paper.PaperMCLoader;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.ServicesManager;
public class VaultFactory {
private final BukkitMCLoader loader;
private final PaperMCLoader loader;
private Vault vault;
public VaultFactory(BukkitMCLoader loader) {
public VaultFactory(PaperMCLoader loader) {
this.loader = loader;
}

View file

@ -1,11 +1,11 @@
name: ${name}
description: ${description}
version: ${version}
main: dev.xhyrom.lighteco.currency.money.bukkit.BukkitMCLoader
main: dev.xhyrom.lighteco.currency.money.paper.PaperMCLoader
author: ${author}
api-version: 1.20
api-version: 1.17
load: STARTUP
softdepend:
- Vault
- lighteco-bukkit
- LightEco

View file

@ -5,7 +5,7 @@ plugins {
repositories {
maven("https://repo.extendedclip.com/content/repositories/placeholderapi")
maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/")
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://oss.sonatype.org/content/repositories/snapshots")
maven("https://oss.sonatype.org/content/repositories/central")
}
@ -13,10 +13,10 @@ repositories {
dependencies {
implementation(project(":lighteco-common"))
implementation("dev.jorel:commandapi-bukkit-shade:9.5.0")
implementation("net.kyori:adventure-platform-bukkit:4.2.0")
compileOnly("org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT")
compileOnly("io.papermc.paper:paper-api:1.19.1-R0.1-SNAPSHOT")
compileOnly("io.papermc.paper:paper-mojangapi:1.19.1-R0.1-SNAPSHOT")
// PlaceholderAPI
compileOnly("me.clip:placeholderapi:2.11.3")
@ -29,7 +29,9 @@ dependencies {
}
tasks.shadowJar {
relocate("dev.jorel.commandapi", "dev.xhyrom.lighteco.libraries.commandapi")
dependencies {
exclude(dependency("com.mojang:brigadier"))
}
// common
relocate("eu.okaeri.configs", "dev.xhyrom.lighteco.libraries.okaeri.configs")

View file

@ -1,13 +1,12 @@
package dev.xhyrom.lighteco.bukkit;
package dev.xhyrom.lighteco.paper;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig;
import dev.xhyrom.lighteco.bukkit.logger.BukkitLogger;
import dev.xhyrom.lighteco.paper.logger.PaperLogger;
import dev.xhyrom.lighteco.common.plugin.bootstrap.LightEcoBootstrap;
import dev.xhyrom.lighteco.common.plugin.bootstrap.LoaderBootstrap;
import dev.xhyrom.lighteco.common.plugin.logger.PluginLogger;
import dev.xhyrom.lighteco.common.plugin.scheduler.SchedulerAdapter;
import lombok.Getter;
import org.bukkit.OfflinePlayer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.entity.Entity;
@ -17,11 +16,12 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Getter
public class BukkitLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstrap {
private final BukkitLightEcoPlugin plugin = new BukkitLightEcoPlugin(this);
public class PaperLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstrap {
private final PaperLightEcoPlugin plugin = new PaperLightEcoPlugin(this);
@Getter
private final JavaPlugin loader;
@ -29,33 +29,29 @@ public class BukkitLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstr
private final PluginLogger logger;
@Getter
private final SchedulerAdapter scheduler;
@Getter
private BukkitAudiences audience;
public BukkitLightEcoBootstrap(JavaPlugin loader) {
public PaperLightEcoBootstrap(JavaPlugin loader) {
this.loader = loader;
this.logger = new BukkitLogger(loader.getLogger());
this.scheduler = new BukkitSchedulerAdapter(this);
this.logger = new PaperLogger(this.plugin, loader.getLogger());
this.scheduler = new PaperSchedulerAdapter(this);
}
@Override
public void onLoad() {
this.plugin.load();
CommandAPI.onLoad(new CommandAPIBukkitConfig(this.loader)
.verboseOutput(this.getPlugin().getConfig().debug)
);
}
@Override
public void onEnable() {
CommandAPI.onEnable();
this.plugin.enable();
this.audience = BukkitAudiences.create(loader);
this.audience = BukkitAudiences.create(this.loader);
}
@Override
public void onDisable() {
CommandAPI.onDisable();
this.plugin.disable();
}
@ -64,6 +60,16 @@ public class BukkitLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstr
return this.loader.getDataFolder().toPath();
}
@Override
public String getVersion() {
return this.loader.getDescription().getVersion();
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
return Optional.of(this.loader.getServer().getOfflinePlayer(username)).map(OfflinePlayer::getUniqueId);
}
@Override
public boolean isPlayerOnline(UUID uniqueId) {
Player player = this.loader.getServer().getPlayer(uniqueId);

View file

@ -1,14 +1,14 @@
package dev.xhyrom.lighteco.bukkit;
package dev.xhyrom.lighteco.paper;
import org.bukkit.plugin.java.JavaPlugin;
// Used inside plugin.yml
@SuppressWarnings("unused")
public class BukkitLightEcoLoader extends JavaPlugin {
private final BukkitLightEcoBootstrap bootstrap;
public class PaperLightEcoLoader extends JavaPlugin {
private final PaperLightEcoBootstrap bootstrap;
public BukkitLightEcoLoader() {
this.bootstrap = new BukkitLightEcoBootstrap(this);
public PaperLightEcoLoader() {
this.bootstrap = new PaperLightEcoBootstrap(this);
}
@Override

View file

@ -1,12 +1,13 @@
package dev.xhyrom.lighteco.bukkit;
package dev.xhyrom.lighteco.paper;
import dev.xhyrom.lighteco.api.LightEco;
import dev.xhyrom.lighteco.api.manager.ContextManager;
import dev.xhyrom.lighteco.api.platform.Platform;
import dev.xhyrom.lighteco.bukkit.hooks.Hooks;
import dev.xhyrom.lighteco.bukkit.listeners.BukkitConnectionListener;
import dev.xhyrom.lighteco.bukkit.manager.BukkitCommandManager;
import dev.xhyrom.lighteco.bukkit.manager.BukkitContextManager;
import dev.xhyrom.lighteco.paper.hooks.Hooks;
import dev.xhyrom.lighteco.paper.listeners.PaperCommandSuggestionsListener;
import dev.xhyrom.lighteco.paper.listeners.PaperConnectionListener;
import dev.xhyrom.lighteco.paper.manager.PaperCommandManager;
import dev.xhyrom.lighteco.paper.manager.PaperContextManager;
import dev.xhyrom.lighteco.common.manager.currency.StandardCurrencyManager;
import dev.xhyrom.lighteco.common.messaging.MessagingFactory;
import dev.xhyrom.lighteco.common.plugin.AbstractLightEcoPlugin;
@ -17,33 +18,34 @@ import org.bukkit.plugin.ServicePriority;
import org.checkerframework.checker.nullness.qual.NonNull;
@Getter
public class BukkitLightEcoPlugin extends AbstractLightEcoPlugin {
private final BukkitLightEcoBootstrap bootstrap;
public class PaperLightEcoPlugin extends AbstractLightEcoPlugin {
private final PaperLightEcoBootstrap bootstrap;
@Getter
private StandardUserManager userManager;
@Getter
private StandardCurrencyManager currencyManager;
@Getter
private BukkitCommandManager commandManager;
private PaperCommandManager commandManager;
@Getter
private ContextManager<Player> contextManager;
public BukkitLightEcoPlugin(BukkitLightEcoBootstrap bootstrap) {
public PaperLightEcoPlugin(PaperLightEcoBootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
protected void registerListeners() {
this.bootstrap.getLoader().getServer().getPluginManager().registerEvents(new BukkitConnectionListener(this), this.bootstrap.getLoader());
this.bootstrap.getLoader().getServer().getPluginManager().registerEvents(new PaperConnectionListener(this), this.bootstrap.getLoader());
this.bootstrap.getLoader().getServer().getPluginManager().registerEvents(new PaperCommandSuggestionsListener(this), this.bootstrap.getLoader());
}
@Override
public void setupManagers() {
this.userManager = new StandardUserManager(this);
this.currencyManager = new StandardCurrencyManager(this);
this.commandManager = new BukkitCommandManager(this);
this.contextManager = new BukkitContextManager();
this.commandManager = new PaperCommandManager(this);
this.contextManager = new PaperContextManager();
}
@Override
@ -68,6 +70,6 @@ public class BukkitLightEcoPlugin extends AbstractLightEcoPlugin {
@Override
public Platform.@NonNull Type getPlatformType() {
return Platform.Type.BUKKIT;
return Platform.Type.PAPER;
}
}

View file

@ -1,21 +1,20 @@
package dev.xhyrom.lighteco.bukkit;
package dev.xhyrom.lighteco.paper;
import dev.xhyrom.lighteco.common.plugin.scheduler.SchedulerAdapter;
import dev.xhyrom.lighteco.common.plugin.scheduler.SchedulerTask;
import lombok.Getter;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
public class BukkitSchedulerAdapter implements SchedulerAdapter {
public class PaperSchedulerAdapter implements SchedulerAdapter {
private final Executor async;
private final BukkitLightEcoBootstrap bootstrap;
private final PaperLightEcoBootstrap bootstrap;
private final BukkitScheduler scheduler;
public BukkitSchedulerAdapter(BukkitLightEcoBootstrap bootstrap) {
public PaperSchedulerAdapter(PaperLightEcoBootstrap bootstrap) {
this.bootstrap = bootstrap;
this.scheduler = bootstrap.getLoader().getServer().getScheduler();

View file

@ -1,21 +1,15 @@
package dev.xhyrom.lighteco.bukkit.chat;
package dev.xhyrom.lighteco.paper.chat;
import dev.xhyrom.lighteco.common.model.chat.AbstractCommandSender;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
public class BukkitCommandSender extends AbstractCommandSender<CommandSender> {
private final Audience audience;
public BukkitCommandSender(CommandSender sender, BukkitAudiences audienceFactory) {
public class PaperCommandSender extends AbstractCommandSender<CommandSender> {
public PaperCommandSender(CommandSender sender) {
super(sender);
this.audience = audienceFactory.sender(sender);
}
@Override
@ -32,8 +26,13 @@ public class BukkitCommandSender extends AbstractCommandSender<CommandSender> {
return null;
}
@Override
public boolean eligible(String permission) {
return this.delegate.hasPermission(permission);
}
@Override
public void sendMessage(Component message) {
this.audience.sendMessage(message);
this.delegate.sendMessage(message);
}
}

View file

@ -1,6 +1,6 @@
package dev.xhyrom.lighteco.bukkit.hooks;
package dev.xhyrom.lighteco.paper.hooks;
import dev.xhyrom.lighteco.bukkit.BukkitLightEcoPlugin;
import dev.xhyrom.lighteco.paper.PaperLightEcoPlugin;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
@ -8,7 +8,7 @@ import org.bukkit.Bukkit;
public class Hooks {
private static PlaceholderAPIExpansion placeholderAPIExpansion;
public static void register(BukkitLightEcoPlugin plugin) {
public static void register(PaperLightEcoPlugin plugin) {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
placeholderAPIExpansion = new PlaceholderAPIExpansion(plugin);
placeholderAPIExpansion.register();

View file

@ -1,6 +1,6 @@
package dev.xhyrom.lighteco.bukkit.hooks;
package dev.xhyrom.lighteco.paper.hooks;
import dev.xhyrom.lighteco.bukkit.BukkitLightEcoPlugin;
import dev.xhyrom.lighteco.paper.PaperLightEcoPlugin;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import lombok.RequiredArgsConstructor;
@ -11,7 +11,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
@RequiredArgsConstructor
public class PlaceholderAPIExpansion extends PlaceholderExpansion {
private final BukkitLightEcoPlugin plugin;
private final PaperLightEcoPlugin plugin;
@Override
public @NonNull String getIdentifier() {

View file

@ -0,0 +1,55 @@
package dev.xhyrom.lighteco.paper.listeners;
import com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import dev.xhyrom.lighteco.paper.PaperLightEcoPlugin;
import dev.xhyrom.lighteco.paper.util.PaperBrigadier;
import dev.xhyrom.lighteco.paper.chat.PaperCommandSender;
import dev.xhyrom.lighteco.common.command.CommandSource;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class PaperCommandSuggestionsListener implements Listener {
private final PaperLightEcoPlugin plugin;
public PaperCommandSuggestionsListener(PaperLightEcoPlugin plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerSendCommandsEvent(AsyncPlayerSendCommandsEvent<?> event) {
PaperCommandSender sender = new PaperCommandSender(event.getPlayer());
CommandSource source = new CommandSource(this.plugin, sender);
if (event.isAsynchronous() || !event.hasFiredAsync()) {
for (CommandNode<CommandSource> command : this.plugin.getCommandManager().getDispatcher().getRoot().getChildren()) {
PaperBrigadier.removeChild(event.getCommandNode(), command.getName());
PaperBrigadier.removeChild(event.getCommandNode(), this.plugin.getBootstrap().getLoader().getName().toLowerCase() + ":" + command.getName());
if (!command.canUse(source)) continue;
addChild(event, source, command, createClone(command));
addChild(event, source, command, createClone(this.plugin.getBootstrap().getLoader().getName().toLowerCase() + ":" + command.getName(), command));
}
}
}
@SuppressWarnings({"rawtypes", "unchecked", "deprecation"})
private void addChild(AsyncPlayerSendCommandsEvent<?> event, CommandSource source, CommandNode<CommandSource> command, CommandNode<CommandSource> clone) {
for (CommandNode<CommandSource> child : command.getChildren()) {
if (child.canUse(source))
clone.addChild(child);
}
event.getCommandNode().addChild((CommandNode) clone);
}
private CommandNode<CommandSource> createClone(CommandNode<CommandSource> command) {
return createClone(command.getName(), command);
}
private CommandNode<CommandSource> createClone(String name, CommandNode<CommandSource> command) {
return new LiteralCommandNode<>(name, command.getCommand(), command.getRequirement(), command.getRedirect(), command.getRedirectModifier(), command.isFork());
}
}

View file

@ -1,6 +1,6 @@
package dev.xhyrom.lighteco.bukkit.listeners;
package dev.xhyrom.lighteco.paper.listeners;
import dev.xhyrom.lighteco.bukkit.BukkitLightEcoPlugin;
import dev.xhyrom.lighteco.paper.PaperLightEcoPlugin;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.model.user.User;
import net.kyori.adventure.text.Component;
@ -14,11 +14,11 @@ import org.bukkit.event.player.PlayerQuitEvent;
import java.util.UUID;
public class BukkitConnectionListener implements Listener {
private final BukkitLightEcoPlugin plugin;
public class PaperConnectionListener implements Listener {
private final PaperLightEcoPlugin plugin;
private final MiniMessage miniMessage = MiniMessage.miniMessage();
public BukkitConnectionListener(BukkitLightEcoPlugin plugin) {
public PaperConnectionListener(PaperLightEcoPlugin plugin) {
this.plugin = plugin;
}

View file

@ -1,14 +1,17 @@
package dev.xhyrom.lighteco.bukkit.logger;
package dev.xhyrom.lighteco.paper.logger;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import dev.xhyrom.lighteco.common.plugin.logger.PluginLogger;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BukkitLogger implements PluginLogger {
public class PaperLogger implements PluginLogger {
private final LightEcoPlugin plugin;
private final Logger logger;
public BukkitLogger(Logger logger) {
public PaperLogger(LightEcoPlugin plugin, Logger logger) {
this.plugin = plugin;
this.logger = logger;
}
@ -22,6 +25,20 @@ public class BukkitLogger implements PluginLogger {
this.logger.info(String.format(message, args));
}
@Override
public void debug(String message) {
if (!this.plugin.getConfig().debug) return;
info(message);
}
@Override
public void debug(String message, Object... args) {
if (!this.plugin.getConfig().debug) return;
info(message, args);
}
@Override
public void warn(String message) {
this.logger.log(Level.WARNING, message);

View file

@ -0,0 +1,64 @@
package dev.xhyrom.lighteco.paper.manager;
import com.mojang.brigadier.ParseResults;
import dev.xhyrom.lighteco.paper.chat.PaperCommandSender;
import dev.xhyrom.lighteco.common.command.CommandManager;
import dev.xhyrom.lighteco.common.command.CommandSource;
import dev.xhyrom.lighteco.common.command.abstraction.Command;
import dev.xhyrom.lighteco.common.model.currency.Currency;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import dev.xhyrom.lighteco.paper.util.PaperCommandMapUtil;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.List;
public class PaperCommandManager extends CommandManager {
private final PaperCommandMapUtil commandMapUtil;
public PaperCommandManager(LightEcoPlugin plugin) {
super(plugin);
this.commandMapUtil = new PaperCommandMapUtil(plugin);
}
@Override
protected void register(Command command) {
super.register(command);
CommandExecutor executor = (sender, bukkitCommand, s, args) -> {
if (s.startsWith("lighteco:")) {
s = s.substring(9);
}
execute(new PaperCommandSender(sender), s, args);
return true;
};
TabCompleter completer = (sender, bukkitCommand, s, args) -> {
final List<String> suggestions = new ArrayList<>();
final CommandSource source = new CommandSource(plugin, new PaperCommandSender(sender));
final ParseResults<CommandSource> parseResults = getDispatcher().parse(
command.getName() + (args.length > 0 ? " " + String.join(" ", args) : ""),
source
);
getDispatcher().getCompletionSuggestions(
parseResults
).join().getList().forEach(suggestion -> suggestions.add(suggestion.getText()));
return suggestions;
};
List<String> aliases = new ArrayList<>(command.getAliases());
aliases.add(command.getName());
this.commandMapUtil.register(
executor,
completer,
aliases
);
}
}

View file

@ -1,4 +1,4 @@
package dev.xhyrom.lighteco.bukkit.manager;
package dev.xhyrom.lighteco.paper.manager;
import dev.xhyrom.lighteco.api.manager.ContextManager;
import org.bukkit.entity.Player;
@ -6,7 +6,7 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.UUID;
public class BukkitContextManager implements ContextManager<Player> {
public class PaperContextManager implements ContextManager<Player> {
@Override
public @NonNull UUID getPlayerUniqueId(@NonNull Player player) {
return player.getUniqueId();

View file

@ -0,0 +1,41 @@
package dev.xhyrom.lighteco.paper.util;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import java.lang.reflect.Field;
import java.util.Map;
public class PaperBrigadier {
private static final Field CHILDREN_FIELD;
private static final Field LITERALS_FIELD;
private static final Field ARGUMENTS_FIELD;
private static final Field[] CHILDREN_FIELDS;
static {
try {
CHILDREN_FIELD = CommandNode.class.getDeclaredField("children");
LITERALS_FIELD = CommandNode.class.getDeclaredField("literals");
ARGUMENTS_FIELD = CommandNode.class.getDeclaredField("arguments");
CHILDREN_FIELDS = new Field[]{CHILDREN_FIELD, LITERALS_FIELD, ARGUMENTS_FIELD};
for (Field field : CHILDREN_FIELDS) {
field.setAccessible(true);
}
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("unchecked")
public static void removeChild(RootCommandNode<?> root, String name) {
try {
for (Field field : CHILDREN_FIELDS) {
Map<String, ?> children = (Map<String, ?>) field.get(root);
children.remove(name);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}

View file

@ -0,0 +1,56 @@
package dev.xhyrom.lighteco.paper.util;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import org.bukkit.command.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
public class PaperCommandMapUtil {
private static final Constructor<PluginCommand> COMMAND_CONSTRUCTOR;
static {
try {
COMMAND_CONSTRUCTOR = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
COMMAND_CONSTRUCTOR.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e);
}
}
private final LightEcoPlugin plugin;
public PaperCommandMapUtil(LightEcoPlugin plugin) {
this.plugin = plugin;
}
public void register(CommandExecutor executor, TabCompleter completer, List<String> aliases) {
Plugin bukkitPlugin = (JavaPlugin) this.plugin.getBootstrap().getLoader();
CommandMap commandMap = bukkitPlugin.getServer().getCommandMap();
Map<String, Command> knownCommands = commandMap.getKnownCommands();
for (String name : aliases) {
if (!name.toLowerCase().equals(name)) {
throw new IllegalArgumentException("Command aliases must be lowercase! (name: " + name + ")");
}
try {
PluginCommand command = COMMAND_CONSTRUCTOR.newInstance(name, bukkitPlugin);
commandMap.register(bukkitPlugin.getName().toLowerCase(), command);
knownCommands.put(bukkitPlugin.getName().toLowerCase() + ":" + name.toLowerCase(), command);
knownCommands.put(name, command);
command.setLabel(name);
command.setExecutor(executor);
command.setTabCompleter(completer);
commandMap.register(bukkitPlugin.getName(), command);
} catch (ReflectiveOperationException e) {
this.plugin.getBootstrap().getLogger().error("Failed to register command: %s", e);
}
}
}
}

View file

@ -1,9 +1,9 @@
name: ${name}
name: ${coreName}
description: ${description}
version: ${version}
main: dev.xhyrom.lighteco.bukkit.BukkitLightEcoLoader
main: dev.xhyrom.lighteco.paper.PaperLightEcoLoader
author: ${author}
api-version: 1.16
api-version: 1.17
load: STARTUP
softdepend:

View file

@ -3,15 +3,22 @@ rootProject.name = "lighteco-parent"
sequenceOf(
"api",
"common",
"bukkit",
"bukkittest",
"paper",
"sponge-8",
"currency-money"
"currency-money",
"test"
).forEach {
include("lighteco-$it")
project(":lighteco-$it").projectDir = file(it)
}
sequenceOf(
"paper"
).forEach {
include("lighteco-test-$it")
project(":lighteco-test-$it").projectDir = file("test/$it")
}
pluginManagement {
repositories {
mavenLocal()

View file

@ -12,6 +12,7 @@ import org.spongepowered.plugin.builtin.jvm.Plugin;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Plugin("lighteco-sponge")
@ -60,6 +61,16 @@ public class SpongeLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstr
return null;
}
@Override
public String getVersion() {
return null;
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
return Optional.empty();
}
@Override
public boolean isPlayerOnline(UUID uniqueId) {
return false;

View file

@ -3,7 +3,7 @@ package dev.xhyrom.lighteco.sponge;
import dev.xhyrom.lighteco.api.LightEco;
import dev.xhyrom.lighteco.api.manager.ContextManager;
import dev.xhyrom.lighteco.api.platform.Platform;
import dev.xhyrom.lighteco.common.manager.command.CommandManager;
import dev.xhyrom.lighteco.common.command.CommandManager;
import dev.xhyrom.lighteco.common.manager.currency.StandardCurrencyManager;
import dev.xhyrom.lighteco.common.manager.user.StandardUserManager;
import dev.xhyrom.lighteco.common.messaging.MessagingFactory;

View file

@ -6,8 +6,17 @@ plugins {
}
server {
version = "1.20.1"
type = "paper"
version = "1.20.6"
type = "purpur"
// Minecraft 1.20.6 requires java 21
java {
targetCompatibility = JavaVersion.VERSION_21
sourceCompatibility = JavaVersion.VERSION_21
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
}
repositories {

View file

@ -1,4 +1,4 @@
package dev.xhyrom.lighteco.bukkittest;
package dev.xhyrom.lighteco.test.paper;
import dev.xhyrom.lighteco.api.model.currency.Currency;

View file

@ -1,4 +1,4 @@
package dev.xhyrom.lighteco.bukkittest;
package dev.xhyrom.lighteco.test.paper;
import dev.xhyrom.lighteco.api.model.currency.Currency;
import dev.xhyrom.lighteco.api.model.user.User;
@ -18,7 +18,7 @@ public class TestCurrency2 implements Currency {
@Override
public boolean isPayable() {
return true;
return false;
}
@Override

View file

@ -1,4 +1,4 @@
package dev.xhyrom.lighteco.bukkittest;
package dev.xhyrom.lighteco.test.paper;
import dev.xhyrom.lighteco.api.LightEco;
import dev.xhyrom.lighteco.api.LightEcoProvider;

View file

@ -1,10 +1,10 @@
name: ${name}
description: ${description}
version: ${version}
main: dev.xhyrom.lighteco.bukkittest.TestPlugin
main: dev.xhyrom.lighteco.test.paper.TestPlugin
author: ${author}
api-version: 1.20
softdepend:
- Vault
- lighteco-bukkit
- LightEco