Add shared module for Fabric, NeoForge and Forge

This commit is contained in:
Luck committed 2025-12-22 22:14:08 +00:00
1 parent 2adb058e96
commit 2f77191875
68 files changed
+1227 -2634

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
plugins {
alias(libs.plugins.licenser) apply false
alias(libs.plugins.loom) apply false
}
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
-1
View File
@@ -37,7 +37,6 @@ dependencies {
compileOnly project(':common:loader-utils')
compileOnly 'com.mojang:brigadier:1.0.18'
compileOnly 'org.slf4j:slf4j-api:1.7.30'
compileOnly 'org.apache.logging.log4j:log4j-api:2.14.0'
+22
View File
@@ -0,0 +1,22 @@
plugins {
alias(libs.plugins.loom)
}
sourceCompatibility = 21
targetCompatibility = 21
repositories {
maven { url 'https://maven.fabricmc.net/' }
}
dependencies {
// https://modmuss50.me/fabric.html
minecraft 'com.mojang:minecraft:1.21.11'
mappings loom.officialMojangMappings()
implementation project(':common')
}
remapJar {
targetNamespace = 'named'
}
@@ -0,0 +1,102 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.minecraft;
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.NameAndId;
import net.minecraft.server.players.PlayerList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public abstract class MinecraftLuckPermsBootstrap implements LuckPermsBootstrap {
public abstract Optional<MinecraftServer> getServer();
@Override
public final Optional<ServerPlayer> getPlayer(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList).map(playerList -> playerList.getPlayer(uniqueId));
}
@Override
public final Optional<UUID> lookupUniqueId(String username) {
return getServer().map(server -> server.services().nameToIdCache())
.flatMap(resolver -> resolver.get(username)).map(NameAndId::id);
}
@Override
public final Optional<String> lookupUsername(UUID uniqueId) {
return getServer().map(server -> server.services().nameToIdCache())
.flatMap(resolver -> resolver.get(uniqueId)).map(NameAndId::name);
}
@Override
public final int getPlayerCount() {
return getServer().map(MinecraftServer::getPlayerCount).orElse(0);
}
@Override
public final Collection<String> getPlayerList() {
return getServer().map(MinecraftServer::getPlayerList)
.map(PlayerList::getPlayers)
.map(players -> {
List<String> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().name());
}
return list;
})
.orElse(Collections.emptyList());
}
@Override
public final Collection<UUID> getOnlinePlayers() {
return getServer().map(MinecraftServer::getPlayerList)
.map(PlayerList::getPlayers)
.map(players -> {
List<UUID> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().id());
}
return list;
})
.orElse(Collections.emptyList());
}
@Override
public final boolean isPlayerOnline(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList)
.map(s -> s.getPlayer(uniqueId) != null)
.orElse(false);
}
}
@@ -0,0 +1,127 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.minecraft;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.minecraft.calculator.MinecraftCalculatorFactory;
import me.lucko.luckperms.common.minecraft.context.MinecraftContextManager;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.model.manager.group.StandardGroupManager;
import me.lucko.luckperms.common.model.manager.track.StandardTrackManager;
import me.lucko.luckperms.common.model.manager.user.StandardUserManager;
import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
import me.lucko.luckperms.common.sender.DummyConsoleSender;
import me.lucko.luckperms.common.sender.Sender;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.players.PlayerList;
import java.util.Optional;
import java.util.stream.Stream;
public abstract class MinecraftLuckPermsPlugin<P extends MinecraftLuckPermsPlugin<P, B>, B extends MinecraftLuckPermsBootstrap> extends AbstractLuckPermsPlugin {
protected final B bootstrap;
private StandardUserManager userManager;
private StandardGroupManager groupManager;
private StandardTrackManager trackManager;
protected MinecraftLuckPermsPlugin(B bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public final B getBootstrap() {
return this.bootstrap;
}
@Override
public abstract MinecraftContextManager getContextManager();
public abstract MinecraftSenderFactory<P> getSenderFactory();
@Override
protected void setupManagers() {
this.userManager = new StandardUserManager(this);
this.groupManager = new StandardGroupManager(this);
this.trackManager = new StandardTrackManager(this);
}
@Override
protected CalculatorFactory provideCalculatorFactory() {
return new MinecraftCalculatorFactory(this);
}
@Override
public final Optional<QueryOptions> getQueryOptionsForUser(User user) {
return this.bootstrap.getPlayer(user.getUniqueId()).map(player -> getContextManager().getQueryOptions(player));
}
@Override
public final Stream<Sender> getOnlineSenders() {
return Stream.concat(
Stream.of(getConsoleSender()),
this.bootstrap.getServer()
.map(MinecraftServer::getPlayerList)
.map(PlayerList::getPlayers)
.stream()
.flatMap(players -> players.stream()
.map(player -> getSenderFactory().wrap(player.createCommandSourceStack()))
)
);
}
@Override
public final Sender getConsoleSender() {
return this.bootstrap.getServer()
.map(server -> getSenderFactory().wrap(server.createCommandSourceStack()))
.orElseGet(() -> new DummyConsoleSender(this) {
@Override
public void sendMessage(Component message) {
MinecraftLuckPermsPlugin.this.bootstrap.getPluginLogger().info(PlainTextComponentSerializer.plainText().serialize(TranslationManager.render(message)));
}
});
}
@Override
public StandardUserManager getUserManager() {
return this.userManager;
}
@Override
public StandardGroupManager getGroupManager() {
return this.groupManager;
}
@Override
public StandardTrackManager getTrackManager() {
return this.trackManager;
}
}
@@ -23,16 +23,16 @@
* SOFTWARE.
*/
package me.lucko.luckperms.neoforge;
package me.lucko.luckperms.common.minecraft;
import me.lucko.luckperms.common.plugin.scheduler.AbstractJavaScheduler;
import java.util.concurrent.Executor;
public class NeoForgeSchedulerAdapter extends AbstractJavaScheduler {
public class MinecraftSchedulerAdapter extends AbstractJavaScheduler {
private final Executor sync;
public NeoForgeSchedulerAdapter(LPNeoForgeBootstrap bootstrap) {
public MinecraftSchedulerAdapter(MinecraftLuckPermsBootstrap bootstrap) {
super(bootstrap);
this.sync = r -> bootstrap.getServer().orElseThrow(() -> new IllegalStateException("Server not ready")).executeBlocking(r);
}
@@ -41,5 +41,4 @@ public class NeoForgeSchedulerAdapter extends AbstractJavaScheduler {
public Executor sync() {
return this.sync;
}
}
@@ -0,0 +1,109 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.minecraft;
import com.mojang.serialization.JsonOps;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.sender.SenderFactory;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.rcon.RconConsoleSource;
import java.util.Locale;
import java.util.UUID;
public abstract class MinecraftSenderFactory<P extends LuckPermsPlugin> extends SenderFactory<P, CommandSourceStack> {
private final P plugin;
public MinecraftSenderFactory(P plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
protected P getPlugin() {
return this.plugin;
}
protected abstract CommandSource getSource(CommandSourceStack sender);
@Override
protected UUID getUniqueId(CommandSourceStack commandSource) {
if (commandSource.getEntity() != null) {
return commandSource.getEntity().getUUID();
}
return Sender.CONSOLE_UUID;
}
@Override
protected String getName(CommandSourceStack commandSource) {
String name = commandSource.getTextName();
if (commandSource.getEntity() != null && name.equals("Server")) {
return Sender.CONSOLE_NAME;
}
return name;
}
@Override
protected void sendMessage(CommandSourceStack sender, Component message) {
Locale locale = sender.getEntity() instanceof ServerPlayer player
? TranslationManager.parseLocale(player.clientInformation().language())
: null;
sender.sendSuccess(() -> toNativeText(TranslationManager.render(message, locale)), false);
}
@Override
protected boolean hasPermission(CommandSourceStack commandSource, String node) {
return getPermissionValue(commandSource, node).asBoolean();
}
@Override
protected void performCommand(CommandSourceStack sender, String command) {
sender.getServer().getCommands().performPrefixedCommand(sender, command);
}
@Override
protected boolean isConsole(CommandSourceStack sender) {
CommandSource output = getSource(sender);
return output == sender.getServer() || // Console
output.getClass() == RconConsoleSource.class || // Rcon
(output == CommandSource.NULL && sender.getTextName().equals("")); // Functions
}
public static net.minecraft.network.chat.Component toNativeText(Component component) {
return ComponentSerialization.CODEC.decode(
RegistryAccess.EMPTY.createSerializationContext(JsonOps.INSTANCE),
GsonComponentSerializer.gson().serializeToTree(component)
).getOrThrow(IllegalArgumentException::new).getFirst();
}
}
@@ -23,7 +23,7 @@
* SOFTWARE.
*/
package me.lucko.luckperms.forge.calculator;
package me.lucko.luckperms.common.minecraft.calculator;
import me.lucko.luckperms.common.cacheddata.CacheMetadata;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
@@ -34,17 +34,17 @@ import me.lucko.luckperms.common.calculator.processor.RegexProcessor;
import me.lucko.luckperms.common.calculator.processor.SpongeWildcardProcessor;
import me.lucko.luckperms.common.calculator.processor.WildcardProcessor;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.forge.LPForgePlugin;
import me.lucko.luckperms.forge.context.ForgeContextManager;
import me.lucko.luckperms.common.minecraft.context.MinecraftContextManager;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import net.luckperms.api.query.QueryOptions;
import java.util.ArrayList;
import java.util.List;
public class ForgeCalculatorFactory implements CalculatorFactory {
private final LPForgePlugin plugin;
public class MinecraftCalculatorFactory implements CalculatorFactory {
private final LuckPermsPlugin plugin;
public ForgeCalculatorFactory(LPForgePlugin plugin) {
public MinecraftCalculatorFactory(LuckPermsPlugin plugin) {
this.plugin = plugin;
}
@@ -66,12 +66,11 @@ public class ForgeCalculatorFactory implements CalculatorFactory {
processors.add(new SpongeWildcardProcessor());
}
boolean integratedOwner = queryOptions.option(ForgeContextManager.INTEGRATED_SERVER_OWNER).orElse(false);
boolean integratedOwner = queryOptions.option(MinecraftContextManager.INTEGRATED_SERVER_OWNER).orElse(false);
if (integratedOwner && this.plugin.getConfiguration().get(ConfigKeys.INTEGRATED_SERVER_OWNER_BYPASSES_CHECKS)) {
processors.add(ServerOwnerProcessor.INSTANCE);
}
return new PermissionCalculator(this.plugin, metadata, processors);
}
}
@@ -23,7 +23,7 @@
* SOFTWARE.
*/
package me.lucko.luckperms.neoforge.calculator;
package me.lucko.luckperms.common.minecraft.calculator;
import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.calculator.processor.AbstractPermissionProcessor;
@@ -31,8 +31,7 @@ import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import net.luckperms.api.util.Tristate;
/**
* Permission processor which is added to the owner of an Integrated server to
* simply return true if no other processors match.
* Permission processor which is added to the owner of an integrated server to simply return true if no other processors match.
*/
public class ServerOwnerProcessor extends AbstractPermissionProcessor implements PermissionProcessor {
private static final TristateResult TRUE_RESULT = new TristateResult.Factory(ServerOwnerProcessor.class).result(Tristate.TRUE);
@@ -47,5 +46,4 @@ public class ServerOwnerProcessor extends AbstractPermissionProcessor implements
public TristateResult hasPermission(String permission) {
return TRUE_RESULT;
}
}
@@ -23,15 +23,15 @@
* SOFTWARE.
*/
package me.lucko.luckperms.neoforge.util;
package me.lucko.luckperms.common.minecraft.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.graph.Graph;
import me.lucko.luckperms.common.graph.TraversalAlgorithm;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.commands.CommandSourceStack;
@@ -69,7 +69,7 @@ public final class BrigadierInjector {
* @param plugin the plugin
* @param dispatcher the command dispatcher
*/
public static void inject(LPNeoForgePlugin plugin, CommandDispatcher<CommandSourceStack> dispatcher) {
public static void inject(MinecraftLuckPermsPlugin<?, ?> plugin, CommandDispatcher<CommandSourceStack> dispatcher) {
Iterable<CommandNodeWithParent> tree = CommandNodeGraph.INSTANCE.traverse(
TraversalAlgorithm.DEPTH_FIRST_PRE_ORDER,
new CommandNodeWithParent(null, dispatcher.getRoot())
@@ -104,7 +104,7 @@ public final class BrigadierInjector {
while (node != null) {
if (node.node instanceof LiteralCommandNode) {
if (builder.length() != 0) {
if (!builder.isEmpty()) {
builder.insert(0, '.');
}
@@ -115,7 +115,7 @@ public final class BrigadierInjector {
node = node.parent;
}
if (builder.length() == 0) {
if (builder.isEmpty()) {
return null;
}
@@ -128,11 +128,11 @@ public final class BrigadierInjector {
* delegating to the existing requirement.
*/
private static final class InjectedPermissionRequirement implements Predicate<CommandSourceStack> {
private final LPNeoForgePlugin plugin;
private final MinecraftLuckPermsPlugin<?, ?> plugin;
private final String permission;
private final Predicate<CommandSourceStack> delegate;
private InjectedPermissionRequirement(LPNeoForgePlugin plugin, String permission, Predicate<CommandSourceStack> delegate) {
private InjectedPermissionRequirement(MinecraftLuckPermsPlugin<?, ?> plugin, String permission, Predicate<CommandSourceStack> delegate) {
this.plugin = plugin;
this.permission = permission;
this.delegate = delegate;
@@ -0,0 +1,178 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.minecraft.command;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.command.CommandManager;
import me.lucko.luckperms.common.command.utils.ArgumentTokenizer;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import net.minecraft.server.permissions.Permission;
import net.minecraft.server.permissions.PermissionLevel;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CompletableFuture;
public class MinecraftCommandExecutor extends CommandManager implements Command<CommandSourceStack>, SuggestionProvider<CommandSourceStack> {
private static final String[] COMMAND_ALIASES = new String[]{"luckperms", "lp", "perm", "perms", "permission", "permissions"};
private final MinecraftLuckPermsPlugin<?, ?> plugin;
protected MinecraftCommandExecutor(MinecraftLuckPermsPlugin<?, ?> plugin) {
super(plugin);
this.plugin = plugin;
}
public void register(CommandDispatcher<CommandSourceStack> dispatcher) {
for (String alias : COMMAND_ALIASES) {
LiteralCommandNode<CommandSourceStack> command = Commands.literal(alias).executes(this).build();
ArgumentCommandNode<CommandSourceStack, String> argument = Commands.argument("args", StringArgumentType.greedyString())
.suggests(this)
.executes(this)
.build();
command.addChild(argument);
dispatcher.getRoot().addChild(command);
}
}
@Override
public int run(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
CommandSourceStack source = context.getSource();
Sender sender = this.plugin.getSenderFactory().wrap(source);
int start = context.getRange().getStart();
String buffer = context.getInput().substring(start);
List<String> arguments;
if (this.plugin.getConfiguration().get(ConfigKeys.RESOLVE_COMMAND_SELECTORS)) {
arguments = resolveSelectors(source, ArgumentTokenizer.EXECUTE.tokenizeInput(buffer));
} else {
arguments = ArgumentTokenizer.EXECUTE.tokenizeInput(buffer);
}
String label = arguments.remove(0);
if (label.startsWith("/")) {
label = label.substring(1);
}
executeCommand(sender, label, arguments);
return Command.SINGLE_SUCCESS;
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) throws CommandSyntaxException {
CommandSourceStack source = context.getSource();
Sender sender = this.plugin.getSenderFactory().wrap(source);
int idx = builder.getStart();
String buffer = builder.getInput().substring(idx);
idx += buffer.length();
List<String> arguments = ArgumentTokenizer.TAB_COMPLETE.tokenizeInput(buffer);
List<String> resolvedArguments;
if (this.plugin.getConfiguration().get(ConfigKeys.RESOLVE_COMMAND_SELECTORS)) {
resolvedArguments = resolveSelectors(source, new ArrayList<>(arguments));
} else {
resolvedArguments = arguments;
}
if (!arguments.isEmpty() && !resolvedArguments.isEmpty()) {
idx -= arguments.get(arguments.size() - 1).length();
}
List<String> completions = tabCompleteCommand(sender, resolvedArguments);
// Offset the builder from the current string range so suggestions are placed in the right spot
builder = builder.createOffset(idx);
for (String completion : completions) {
builder.suggest(completion);
}
return builder.buildFuture();
}
private List<String> resolveSelectors(CommandSourceStack source, List<String> args) {
// usage of @ selectors requires at least level 2 permission
CommandSourceStack atAllowedSource = ensureSourceCanUseSelectors(source);
for (ListIterator<String> it = args.listIterator(); it.hasNext(); ) {
String arg = it.next();
if (arg.isEmpty() || arg.charAt(0) != '@') {
continue;
}
List<ServerPlayer> matchedPlayers;
try {
matchedPlayers = EntityArgument.entities().parse(new StringReader(arg)).findPlayers(atAllowedSource);
} catch (CommandSyntaxException e) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args, e);
continue;
}
if (matchedPlayers.isEmpty()) {
continue;
}
if (matchedPlayers.size() > 1) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args +
": ambiguous result (more than one player matched) - " + matchedPlayers);
continue;
}
ServerPlayer player = matchedPlayers.get(0);
it.set(player.getStringUUID());
}
return args;
}
private static CommandSourceStack ensureSourceCanUseSelectors(CommandSourceStack source) {
if (source.permissions().hasPermission(new Permission.HasCommandLevel(PermissionLevel.GAMEMASTERS))) {
return source;
}
return source.withMaximumPermission(LevelBasedPermissionSet.GAMEMASTER);
}
}
@@ -23,23 +23,14 @@
* SOFTWARE.
*/
package me.lucko.luckperms.forge;
package me.lucko.luckperms.common.minecraft.context;
import me.lucko.luckperms.common.plugin.scheduler.AbstractJavaScheduler;
import me.lucko.luckperms.common.context.manager.ContextManager;
import net.luckperms.api.query.OptionKey;
import net.minecraft.server.level.ServerPlayer;
import java.util.concurrent.Executor;
public interface MinecraftContextManager extends ContextManager<ServerPlayer, ServerPlayer> {
public class ForgeSchedulerAdapter extends AbstractJavaScheduler {
private final Executor sync;
public ForgeSchedulerAdapter(LPForgeBootstrap bootstrap) {
super(bootstrap);
this.sync = r -> bootstrap.getServer().orElseThrow(() -> new IllegalStateException("Server not ready")).executeBlocking(r);
}
@Override
public Executor sync() {
return this.sync;
}
OptionKey<Boolean> INTEGRATED_SERVER_OWNER = OptionKey.of("integrated_server_owner", Boolean.class);
}
@@ -0,0 +1,117 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.minecraft.context;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import net.luckperms.api.context.Context;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.ImmutableContextSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.storage.ServerLevelData;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Set;
public class MinecraftPlayerCalculator implements ContextCalculator<ServerPlayer> {
protected final MinecraftLuckPermsPlugin<?, ?> plugin;
protected final boolean gamemode;
protected final boolean world;
protected final boolean dimensionType;
public MinecraftPlayerCalculator(MinecraftLuckPermsPlugin<?, ?> plugin, Set<String> disabled) {
this.plugin = plugin;
this.gamemode = !disabled.contains(DefaultContextKeys.GAMEMODE_KEY);
this.world = !disabled.contains(DefaultContextKeys.WORLD_KEY);
this.dimensionType = !disabled.contains(DefaultContextKeys.DIMENSION_TYPE_KEY);
}
@Override
public void calculate(@NonNull ServerPlayer target, @NonNull ContextConsumer consumer) {
if (this.gamemode) {
GameType gameMode = target.gameMode.getGameModeForPlayer();
consumer.accept(DefaultContextKeys.GAMEMODE_KEY, gameMode.getName());
}
ServerLevel level = target.level();
if (this.dimensionType) {
consumer.accept(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(level.dimension().identifier()));
}
if (this.world) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
this.plugin.getConfiguration().get(ConfigKeys.WORLD_REWRITES).rewriteAndSubmit(levelData.getLevelName(), consumer);
}
}
@Override
public @NonNull ContextSet estimatePotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
if (this.gamemode) {
for (GameType gameType : GameType.values()) {
builder.add(DefaultContextKeys.GAMEMODE_KEY, gameType.getName());
}
}
MinecraftServer server = this.plugin.getBootstrap().getServer().orElse(null);
if (this.dimensionType && server != null) {
server.registryAccess().lookup(Registries.DIMENSION_TYPE).ifPresent(registry -> {
for (Identifier id : registry.keySet()) {
builder.add(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(id));
}
});
}
if (this.world && server != null) {
for (ServerLevel level : server.getAllLevels()) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
if (Context.isValidValue(levelData.getLevelName())) {
builder.add(DefaultContextKeys.WORLD_KEY, levelData.getLevelName());
}
}
}
return builder.build();
}
private static String getContextKey(Identifier key) {
if (key.getNamespace().equals("minecraft")) {
return key.getPath();
}
return key.toString();
}
}
@@ -23,12 +23,12 @@
* SOFTWARE.
*/
package me.lucko.luckperms.neoforge.listeners;
package me.lucko.luckperms.common.minecraft.listeners;
import me.lucko.luckperms.common.api.implementation.ApiUser;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
@@ -37,12 +37,12 @@ import net.minecraft.server.level.ServerPlayer;
import java.util.Map;
public class NeoForgeAutoOpListener implements LuckPermsEventListener {
public class MinecraftAutoOpListener implements LuckPermsEventListener {
private static final String NODE = "luckperms.autoop";
private final LPNeoForgePlugin plugin;
private final MinecraftLuckPermsPlugin<?, ?> plugin;
public NeoForgeAutoOpListener(LPNeoForgePlugin plugin) {
public MinecraftAutoOpListener(MinecraftLuckPermsPlugin<?, ?> plugin) {
this.plugin = plugin;
}
@@ -23,34 +23,36 @@
* SOFTWARE.
*/
package me.lucko.luckperms.forge.listeners;
package me.lucko.luckperms.common.minecraft.listeners;
import com.github.benmanes.caffeine.cache.LoadingCache;
import me.lucko.luckperms.common.api.implementation.ApiGroup;
import me.lucko.luckperms.common.cache.BufferedRequest;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.util.CaffeineFactory;
import me.lucko.luckperms.forge.LPForgePlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.group.GroupDataRecalculateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Calls {@link net.minecraft.server.players.PlayerList#sendPlayerPermissionLevel(ServerPlayer)} when a players permissions change.
* Calls {@link PlayerList#sendPlayerPermissionLevel(ServerPlayer)} when a players permissions change.
*/
public class ForgeCommandListUpdater implements LuckPermsEventListener {
private final LPForgePlugin plugin;
public class MinecraftCommandListUpdater implements LuckPermsEventListener {
private final MinecraftLuckPermsPlugin<?, ?> plugin;
private final LoadingCache<UUID, SendBuffer> sendingBuffers = CaffeineFactory.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.build(SendBuffer::new);
public ForgeCommandListUpdater(LPForgePlugin plugin) {
public MinecraftCommandListUpdater(MinecraftLuckPermsPlugin<?, ?> plugin) {
this.plugin = plugin;
}
@@ -66,11 +68,11 @@ public class ForgeCommandListUpdater implements LuckPermsEventListener {
}
private void onGroupDataRecalculate(GroupDataRecalculateEvent e) {
plugin.getUserManager().getAll().values().forEach(user -> {
for (User user : this.plugin.getUserManager().getAll().values()) {
if (user.resolveInheritanceTree(user.getQueryOptions()).contains(ApiGroup.cast(e.getGroup()))) {
requestUpdate(user.getUniqueId());
}
});
}
}
private void onContextUpdate(ContextUpdateEvent e) {
@@ -82,30 +84,24 @@ public class ForgeCommandListUpdater implements LuckPermsEventListener {
return;
}
// Buffer the request to send a commands update.
SendBuffer sendBuffer = this.sendingBuffers.get(uniqueId);
if (sendBuffer != null) {
sendBuffer.request();
}
this.sendingBuffers.get(uniqueId).request();
}
// Called when the buffer times out.
private void sendUpdate(UUID uniqueId) {
this.plugin.getBootstrap().getScheduler().sync().execute(() -> {
this.plugin.getBootstrap().getPlayer(uniqueId).ifPresent(player -> {
MinecraftServer server = player.level().getServer();
if (server != null) {
this.plugin.getBootstrap().getScheduler().sync().execute(() ->
this.plugin.getBootstrap().getPlayer(uniqueId).ifPresent(player -> {
MinecraftServer server = player.level().getServer();
server.getPlayerList().sendPlayerPermissionLevel(player);
}
});
});
})
);
}
private final class SendBuffer extends BufferedRequest<Void> {
private final UUID uniqueId;
SendBuffer(UUID uniqueId) {
super(500, TimeUnit.MILLISECONDS, ForgeCommandListUpdater.this.plugin.getBootstrap().getScheduler());
super(500, TimeUnit.MILLISECONDS, MinecraftCommandListUpdater.this.plugin.getBootstrap().getScheduler());
this.uniqueId = uniqueId;
}
@@ -1,114 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.command;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import me.lucko.luckperms.common.command.utils.ArgumentTokenizer;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public abstract class BrigadierCommandExecutor<S> extends CommandManager implements Command<S>, SuggestionProvider<S> {
protected static final String[] COMMAND_ALIASES = new String[]{"luckperms", "lp", "perm", "perms", "permission", "permissions"};
private final LuckPermsPlugin plugin;
protected BrigadierCommandExecutor(LuckPermsPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
public abstract Sender getSender(S source);
public abstract List<String> resolveSelectors(S source, List<String> args);
@Override
public int run(CommandContext<S> context) throws CommandSyntaxException {
S source = context.getSource();
Sender sender = getSender(source);
int start = context.getRange().getStart();
String buffer = context.getInput().substring(start);
List<String> arguments;
if (this.plugin.getConfiguration().get(ConfigKeys.RESOLVE_COMMAND_SELECTORS)) {
arguments = resolveSelectors(source, ArgumentTokenizer.EXECUTE.tokenizeInput(buffer));
} else {
arguments = ArgumentTokenizer.EXECUTE.tokenizeInput(buffer);
}
String label = arguments.remove(0);
if (label.startsWith("/")) {
label = label.substring(1);
}
executeCommand(sender, label, arguments);
return Command.SINGLE_SUCCESS;
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<S> context, SuggestionsBuilder builder) throws CommandSyntaxException {
S source = context.getSource();
Sender sender = getSender(source);
int idx = builder.getStart();
String buffer = builder.getInput().substring(idx);
idx += buffer.length();
List<String> arguments = ArgumentTokenizer.TAB_COMPLETE.tokenizeInput(buffer);
List<String> resolvedArguments;
if (this.plugin.getConfiguration().get(ConfigKeys.RESOLVE_COMMAND_SELECTORS)) {
resolvedArguments = resolveSelectors(source, new ArrayList<>(arguments));
} else {
resolvedArguments = arguments;
}
if (!arguments.isEmpty() && !resolvedArguments.isEmpty()) {
idx -= arguments.get(arguments.size() - 1).length();
}
List<String> completions = tabCompleteCommand(sender, resolvedArguments);
// Offset the builder from the current string range so suggestions are placed in the right spot
builder = builder.createOffset(idx);
for (String completion : completions) {
builder.suggest(completion);
}
return builder.buildFuture();
}
}
@@ -25,244 +25,41 @@
package me.lucko.luckperms.common.context.manager;
import me.lucko.luckperms.common.cache.ExpiringCache;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.context.calculator.ForwardingContextCalculator;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.ImmutableContextSet;
import net.luckperms.api.context.StaticContextCalculator;
import net.luckperms.api.query.QueryOptions;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
/**
* Base implementation of {@link ContextManager}.
* Manages contexts for subjects.
*
* @param <S> the subject type
* @param <P> the player type
*/
public abstract class ContextManager<S, P extends S> {
public interface ContextManager<S, P extends S> {
protected final LuckPermsPlugin plugin;
private final Class<S> subjectClass;
private final Class<P> playerClass;
QueryOptions getQueryOptions(S subject);
private final CalculatorList calculators = new CalculatorList();
ImmutableContextSet getContext(S subject);
// caches static context lookups
private final StaticLookupCache staticLookupCache = new StaticLookupCache();
QueryOptions getStaticQueryOptions();
protected ContextManager(LuckPermsPlugin plugin, Class<S> subjectClass, Class<P> playerClass) {
this.plugin = plugin;
this.subjectClass = subjectClass;
this.playerClass = playerClass;
}
ImmutableContextSet getStaticContext();
public Class<S> getSubjectClass() {
return this.subjectClass;
}
UUID getUniqueId(P player);
public Class<P> getPlayerClass() {
return this.playerClass;
}
void signalContextUpdate(S subject);
public abstract UUID getUniqueId(P player);
void invalidateCache(S subject);
public abstract QueryOptions getQueryOptions(S subject);
void registerCalculator(ContextCalculator<? super S> calculator);
public ImmutableContextSet getContext(S subject) {
return getQueryOptions(subject).context();
}
void unregisterCalculator(ContextCalculator<? super S> calculator);
public QueryOptions getStaticQueryOptions() {
return this.staticLookupCache.get();
}
ImmutableContextSet getPotentialContexts();
public ImmutableContextSet getStaticContext() {
return getStaticQueryOptions().context();
}
public void customizeStaticQueryOptions(QueryOptions.Builder builder) {
// overridden
}
public void customizeQueryOptions(S subject, QueryOptions.Builder builder) {
// overridden
}
public void signalContextUpdate(S subject) {
if (subject == null) {
throw new NullPointerException("subject");
}
// invalidate their cache
invalidateCache(subject);
// call event
this.plugin.getEventDispatcher().dispatchContextUpdate(subject);
}
public abstract void invalidateCache(S subject);
public void registerCalculator(ContextCalculator<? super S> calculator) {
String calculatorClass = calculator.getClass().getName();
Set<Predicate<String>> disabledCalculators = this.plugin.getConfiguration().get(ConfigKeys.DISABLED_CONTEXT_CALCULATORS);
for (Predicate<String> disabledPattern : disabledCalculators) {
if (disabledPattern.test(calculatorClass)) {
this.plugin.getLogger().info("Ignoring registration of disabled context calculator: " + calculatorClass);
return;
}
}
this.calculators.add(calculator);
}
public void unregisterCalculator(ContextCalculator<? super S> calculator) {
this.calculators.remove(calculator);
}
protected void callContextCalculator(ContextCalculator<? super S> calculator, S subject, ContextConsumer consumer) {
try {
calculator.calculate(subject, consumer);
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating the context of subject " + subject, e);
}
}
protected void callStaticContextCalculator(StaticContextCalculator calculator, ContextConsumer consumer) {
try {
calculator.calculate(consumer);
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating static contexts", e);
}
}
protected QueryOptions calculate(S subject) {
ImmutableContextSet.Builder accumulator = new ImmutableContextSetImpl.BuilderImpl();
ContextConsumer consumer = accumulator::add;
for (ContextCalculator<? super S> calculator : this.calculators.calculators()) {
callContextCalculator(calculator, subject, consumer);
}
QueryOptions.Builder builder = this.plugin.getConfiguration().get(ConfigKeys.GLOBAL_QUERY_OPTIONS).toBuilder().context(accumulator.build());
customizeQueryOptions(subject, builder);
return builder.build();
}
private QueryOptions calculateStatic() {
ImmutableContextSet.Builder accumulator = new ImmutableContextSetImpl.BuilderImpl();
ContextConsumer consumer = accumulator::add;
for (StaticContextCalculator calculator : this.calculators.staticCalculators()) {
callStaticContextCalculator(calculator, consumer);
}
QueryOptions.Builder builder = this.plugin.getConfiguration().get(ConfigKeys.GLOBAL_QUERY_OPTIONS).toBuilder().context(accumulator.build());
customizeStaticQueryOptions(builder);
return builder.build();
}
public ImmutableContextSet getPotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
for (ContextCalculator<? super S> calculator : this.calculators.calculators()) {
ContextSet potentialContexts;
try {
potentialContexts = calculator.estimatePotentialContexts();
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst estimating potential contexts", e);
continue;
}
builder.addAll(potentialContexts);
}
return builder.build();
}
private final class StaticLookupCache extends ExpiringCache<QueryOptions> {
StaticLookupCache() {
super(50L, TimeUnit.MILLISECONDS);
}
@Override
public @NonNull QueryOptions supply() {
return calculateStatic();
}
}
private static String getCalculatorClass(ContextCalculator<?> calculator) {
Class<?> calculatorClass;
if (calculator instanceof ForwardingContextCalculator) {
calculatorClass = ((ForwardingContextCalculator<?>) calculator).delegate().getClass();
} else {
calculatorClass = calculator.getClass();
}
return calculatorClass.getName();
}
private final class CalculatorList {
private final List<ContextCalculator<? super S>> calculators;
private final List<StaticContextCalculator> staticCalculators;
private volatile ContextCalculator<? super S>[] calculatorsArray;
private volatile StaticContextCalculator[] staticCalculatorsArray;
CalculatorList() {
this.calculators = new ArrayList<>();
this.staticCalculators = new ArrayList<>();
bake();
}
@SuppressWarnings("unchecked")
private void bake() {
this.calculatorsArray = this.calculators.toArray(new ContextCalculator[0]);
this.staticCalculatorsArray = this.staticCalculators.toArray(new StaticContextCalculator[0]);
}
public void add(ContextCalculator<? super S> calculator) {
synchronized (this) {
// calculators registered first should have priority (and be checked last.)
this.calculators.add(0, calculator);
if (calculator instanceof StaticContextCalculator) {
StaticContextCalculator staticCalculator = (StaticContextCalculator) calculator;
this.staticCalculators.add(0, staticCalculator);
}
bake();
}
}
public void remove(ContextCalculator<? super S> calculator) {
synchronized (this) {
this.calculators.remove(calculator);
if (calculator instanceof StaticContextCalculator) {
this.staticCalculators.remove(calculator);
}
bake();
}
}
public ContextCalculator<? super S>[] calculators() {
return this.calculatorsArray;
}
public StaticContextCalculator[] staticCalculators() {
return this.staticCalculatorsArray;
}
}
Class<S> getSubjectClass();
Class<P> getPlayerClass();
}
@@ -0,0 +1,270 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.context.manager;
import me.lucko.luckperms.common.cache.ExpiringCache;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.context.calculator.ForwardingContextCalculator;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.ImmutableContextSet;
import net.luckperms.api.context.StaticContextCalculator;
import net.luckperms.api.query.QueryOptions;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
/**
* Base implementation of {@link ContextManager}.
*
* @param <S> the subject type
* @param <P> the player type
*/
public abstract class ContextManagerBase<S, P extends S> implements ContextManager<S, P> {
protected final LuckPermsPlugin plugin;
private final Class<S> subjectClass;
private final Class<P> playerClass;
private final CalculatorList calculators = new CalculatorList();
// caches static context lookups
private final StaticLookupCache staticLookupCache = new StaticLookupCache();
protected ContextManagerBase(LuckPermsPlugin plugin, Class<S> subjectClass, Class<P> playerClass) {
this.plugin = plugin;
this.subjectClass = subjectClass;
this.playerClass = playerClass;
}
@Override
public Class<S> getSubjectClass() {
return this.subjectClass;
}
@Override
public Class<P> getPlayerClass() {
return this.playerClass;
}
@Override
public ImmutableContextSet getContext(S subject) {
return getQueryOptions(subject).context();
}
@Override
public QueryOptions getStaticQueryOptions() {
return this.staticLookupCache.get();
}
@Override
public ImmutableContextSet getStaticContext() {
return getStaticQueryOptions().context();
}
protected void customizeStaticQueryOptions(QueryOptions.Builder builder) {
// overridden
}
protected void customizeQueryOptions(S subject, QueryOptions.Builder builder) {
// overridden
}
@Override
public void signalContextUpdate(S subject) {
if (subject == null) {
throw new NullPointerException("subject");
}
// invalidate their cache
invalidateCache(subject);
// call event
this.plugin.getEventDispatcher().dispatchContextUpdate(subject);
}
@Override
public void registerCalculator(ContextCalculator<? super S> calculator) {
String calculatorClass = calculator.getClass().getName();
Set<Predicate<String>> disabledCalculators = this.plugin.getConfiguration().get(ConfigKeys.DISABLED_CONTEXT_CALCULATORS);
for (Predicate<String> disabledPattern : disabledCalculators) {
if (disabledPattern.test(calculatorClass)) {
this.plugin.getLogger().info("Ignoring registration of disabled context calculator: " + calculatorClass);
return;
}
}
this.calculators.add(calculator);
}
@Override
public void unregisterCalculator(ContextCalculator<? super S> calculator) {
this.calculators.remove(calculator);
}
protected void callContextCalculator(ContextCalculator<? super S> calculator, S subject, ContextConsumer consumer) {
try {
calculator.calculate(subject, consumer);
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating the context of subject " + subject, e);
}
}
protected void callStaticContextCalculator(StaticContextCalculator calculator, ContextConsumer consumer) {
try {
calculator.calculate(consumer);
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating static contexts", e);
}
}
protected QueryOptions calculate(S subject) {
ImmutableContextSet.Builder accumulator = new ImmutableContextSetImpl.BuilderImpl();
ContextConsumer consumer = accumulator::add;
for (ContextCalculator<? super S> calculator : this.calculators.calculators()) {
callContextCalculator(calculator, subject, consumer);
}
QueryOptions.Builder builder = this.plugin.getConfiguration().get(ConfigKeys.GLOBAL_QUERY_OPTIONS).toBuilder().context(accumulator.build());
customizeQueryOptions(subject, builder);
return builder.build();
}
private QueryOptions calculateStatic() {
ImmutableContextSet.Builder accumulator = new ImmutableContextSetImpl.BuilderImpl();
ContextConsumer consumer = accumulator::add;
for (StaticContextCalculator calculator : this.calculators.staticCalculators()) {
callStaticContextCalculator(calculator, consumer);
}
QueryOptions.Builder builder = this.plugin.getConfiguration().get(ConfigKeys.GLOBAL_QUERY_OPTIONS).toBuilder().context(accumulator.build());
customizeStaticQueryOptions(builder);
return builder.build();
}
@Override
public ImmutableContextSet getPotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
for (ContextCalculator<? super S> calculator : this.calculators.calculators()) {
ContextSet potentialContexts;
try {
potentialContexts = calculator.estimatePotentialContexts();
} catch (Throwable e) {
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst estimating potential contexts", e);
continue;
}
builder.addAll(potentialContexts);
}
return builder.build();
}
private final class StaticLookupCache extends ExpiringCache<QueryOptions> {
StaticLookupCache() {
super(50L, TimeUnit.MILLISECONDS);
}
@Override
public @NonNull QueryOptions supply() {
return calculateStatic();
}
}
private static String getCalculatorClass(ContextCalculator<?> calculator) {
Class<?> calculatorClass;
if (calculator instanceof ForwardingContextCalculator) {
calculatorClass = ((ForwardingContextCalculator<?>) calculator).delegate().getClass();
} else {
calculatorClass = calculator.getClass();
}
return calculatorClass.getName();
}
private final class CalculatorList {
private final List<ContextCalculator<? super S>> calculators;
private final List<StaticContextCalculator> staticCalculators;
private volatile ContextCalculator<? super S>[] calculatorsArray;
private volatile StaticContextCalculator[] staticCalculatorsArray;
CalculatorList() {
this.calculators = new ArrayList<>();
this.staticCalculators = new ArrayList<>();
bake();
}
@SuppressWarnings("unchecked")
private void bake() {
this.calculatorsArray = this.calculators.toArray(new ContextCalculator[0]);
this.staticCalculatorsArray = this.staticCalculators.toArray(new StaticContextCalculator[0]);
}
public void add(ContextCalculator<? super S> calculator) {
synchronized (this) {
// calculators registered first should have priority (and be checked last.)
this.calculators.add(0, calculator);
if (calculator instanceof StaticContextCalculator) {
StaticContextCalculator staticCalculator = (StaticContextCalculator) calculator;
this.staticCalculators.add(0, staticCalculator);
}
bake();
}
}
public void remove(ContextCalculator<? super S> calculator) {
synchronized (this) {
this.calculators.remove(calculator);
if (calculator instanceof StaticContextCalculator) {
this.staticCalculators.remove(calculator);
}
bake();
}
}
public ContextCalculator<? super S>[] calculators() {
return this.calculatorsArray;
}
public StaticContextCalculator[] staticCalculators() {
return this.staticCalculatorsArray;
}
}
}
@@ -34,9 +34,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.concurrent.TimeUnit;
/**
* Implementation of {@link ContextManager} which utilises 'detached' supplier caches stored alongside the subject instances.
* Implementation of {@link ContextManagerBase} which utilises 'detached' supplier caches stored alongside the subject instances.
*/
public abstract class DetachedContextManager<S, P extends S> extends ContextManager<S, P> {
public abstract class DetachedContextManager<S, P extends S> extends ContextManagerBase<S, P> {
private final LoadingCache<S, QueryOptions> fallbackContextsCache = CaffeineFactory.newBuilder()
.expireAfterWrite(50, TimeUnit.MILLISECONDS)
@@ -39,9 +39,9 @@ import java.util.concurrent.TimeUnit;
*/
final class QueryOptionsCache<T> extends ExpiringCache<QueryOptions> implements QueryOptionsSupplier {
private final T subject;
private final ContextManager<T, ?> contextManager;
private final ContextManagerBase<T, ?> contextManager;
QueryOptionsCache(T subject, ContextManager<T, ?> contextManager) {
QueryOptionsCache(T subject, ContextManagerBase<T, ?> contextManager) {
super(50L, TimeUnit.MILLISECONDS); // expire roughly every tick
this.subject = subject;
this.contextManager = contextManager;
@@ -32,7 +32,7 @@ import net.luckperms.api.query.QueryOptions;
import java.util.concurrent.TimeUnit;
public abstract class SimpleContextManager<S, P extends S> extends ContextManager<S, P> {
public abstract class SimpleContextManager<S, P extends S> extends ContextManagerBase<S, P> {
private final LoadingCache<S, QueryOptions> contextsCache = CaffeineFactory.newBuilder()
.expireAfterWrite(50, TimeUnit.MILLISECONDS)
+4 -1
View File
@@ -6,6 +6,8 @@ plugins {
}
archivesBaseName = 'luckperms'
sourceCompatibility = 21
targetCompatibility = 21
repositories {
maven { url 'https://maven.fabricmc.net/' }
@@ -14,7 +16,7 @@ repositories {
dependencies {
// https://modmuss50.me/fabric.html
minecraft 'com.mojang:minecraft:1.21.11'
mappings 'net.fabricmc:yarn:1.21.11+build.1:v2'
mappings loom.officialMojangMappings()
modImplementation 'net.fabricmc:fabric-loader:0.18.2'
Set<String> apiModules = [
@@ -32,6 +34,7 @@ dependencies {
include(modImplementation('me.lucko:fabric-permissions-api:0.6.1'))
implementation project(':common')
implementation project(':common:minecraft')
}
processResources {
@@ -1,76 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.fabric;
import me.lucko.luckperms.common.cacheddata.CacheMetadata;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.calculator.PermissionCalculator;
import me.lucko.luckperms.common.calculator.processor.DirectProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import me.lucko.luckperms.common.calculator.processor.RegexProcessor;
import me.lucko.luckperms.common.calculator.processor.SpongeWildcardProcessor;
import me.lucko.luckperms.common.calculator.processor.WildcardProcessor;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.fabric.calculator.ServerOwnerProcessor;
import me.lucko.luckperms.fabric.context.FabricContextManager;
import net.luckperms.api.query.QueryOptions;
import java.util.ArrayList;
import java.util.List;
public class FabricCalculatorFactory implements CalculatorFactory {
private final LPFabricPlugin plugin;
public FabricCalculatorFactory(LPFabricPlugin plugin) {
this.plugin = plugin;
}
@Override
public PermissionCalculator build(QueryOptions queryOptions, CacheMetadata metadata) {
List<PermissionProcessor> processors = new ArrayList<>(5);
processors.add(new DirectProcessor());
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX)) {
processors.add(new RegexProcessor());
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_WILDCARDS)) {
processors.add(new WildcardProcessor());
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_WILDCARDS_SPONGE)) {
processors.add(new SpongeWildcardProcessor());
}
boolean integratedOwner = queryOptions.option(FabricContextManager.INTEGRATED_SERVER_OWNER).orElse(false);
if (integratedOwner && this.plugin.getConfiguration().get(ConfigKeys.INTEGRATED_SERVER_OWNER_BYPASSES_CHECKS)) {
processors.add(ServerOwnerProcessor.INSTANCE);
}
return new PermissionCalculator(this.plugin, metadata, processors);
}
}
@@ -25,100 +25,15 @@
package me.lucko.luckperms.fabric;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.command.BrigadierCommandExecutor;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.minecraft.command.MinecraftCommandExecutor;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.command.permission.LeveledPermissionPredicate;
import net.minecraft.command.permission.Permission;
import net.minecraft.command.permission.PermissionLevel;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import java.util.List;
import java.util.ListIterator;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
public class FabricCommandExecutor extends BrigadierCommandExecutor<ServerCommandSource> {
private final LPFabricPlugin plugin;
public class FabricCommandExecutor extends MinecraftCommandExecutor {
public FabricCommandExecutor(LPFabricPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
public void register() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
for (String alias : COMMAND_ALIASES) {
LiteralCommandNode<ServerCommandSource> cmd = literal(alias)
.executes(this)
.build();
ArgumentCommandNode<ServerCommandSource, String> args = argument("args", greedyString())
.suggests(this)
.executes(this)
.build();
cmd.addChild(args);
dispatcher.getRoot().addChild(cmd);
}
});
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> register(dispatcher));
}
@Override
public Sender getSender(ServerCommandSource source) {
return this.plugin.getSenderFactory().wrap(source);
}
@Override
public List<String> resolveSelectors(ServerCommandSource source, List<String> args) {
// usage of @ selectors requires at least level 2 permission
ServerCommandSource atAllowedSource = ensureSourceCanUseSelectors(source);
for (ListIterator<String> it = args.listIterator(); it.hasNext(); ) {
String arg = it.next();
if (arg.isEmpty() || arg.charAt(0) != '@') {
continue;
}
List<ServerPlayerEntity> matchedPlayers;
try {
matchedPlayers = EntityArgumentType.entities().parse(new StringReader(arg)).getPlayers(atAllowedSource);
} catch (CommandSyntaxException e) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args, e);
continue;
}
if (matchedPlayers.isEmpty()) {
continue;
}
if (matchedPlayers.size() > 1) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args +
": ambiguous result (more than one player matched) - " + matchedPlayers);
continue;
}
ServerPlayerEntity player = matchedPlayers.get(0);
it.set(player.getUuidAsString());
}
return args;
}
private static ServerCommandSource ensureSourceCanUseSelectors(ServerCommandSource source) {
if (source.getPermissions().hasPermission(new Permission.Level(PermissionLevel.GAMEMASTERS))) {
return source;
}
return source.withAdditionalPermissions(LeveledPermissionPredicate.GAMEMASTERS);
}
}
@@ -1,44 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.fabric;
import me.lucko.luckperms.common.plugin.scheduler.AbstractJavaScheduler;
import java.util.concurrent.Executor;
public class FabricSchedulerAdapter extends AbstractJavaScheduler {
private final Executor sync;
public FabricSchedulerAdapter(LPFabricBootstrap bootstrap) {
super(bootstrap);
this.sync = r -> bootstrap.getServer().orElseThrow(() -> new IllegalStateException("Server not ready")).submitAndJoin(r);
}
@Override
public Executor sync() {
return this.sync;
}
}
@@ -25,104 +25,29 @@
package me.lucko.luckperms.fabric;
import com.mojang.serialization.JsonOps;
import me.lucko.fabric.api.permissions.v0.Permissions;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.sender.SenderFactory;
import me.lucko.luckperms.fabric.mixin.ServerCommandSourceAccessor;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import me.lucko.luckperms.common.minecraft.MinecraftSenderFactory;
import me.lucko.luckperms.fabric.mixin.CommandSourceStackAccessor;
import net.luckperms.api.util.Tristate;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.server.command.CommandOutput;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.rcon.RconCommandOutput;
import net.minecraft.text.Text;
import net.minecraft.text.TextCodecs;
import java.util.Locale;
import java.util.UUID;
public class FabricSenderFactory extends SenderFactory<LPFabricPlugin, ServerCommandSource> {
private final LPFabricPlugin plugin;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
public class FabricSenderFactory extends MinecraftSenderFactory<LPFabricPlugin> {
public FabricSenderFactory(LPFabricPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
protected LPFabricPlugin getPlugin() {
return this.plugin;
protected CommandSource getSource(CommandSourceStack sender) {
return ((CommandSourceStackAccessor) sender).getSource();
}
@Override
protected UUID getUniqueId(ServerCommandSource commandSource) {
if (commandSource.getEntity() != null) {
return commandSource.getEntity().getUuid();
}
return Sender.CONSOLE_UUID;
}
@Override
protected String getName(ServerCommandSource commandSource) {
String name = commandSource.getName();
if (commandSource.getEntity() != null && name.equals("Server")) {
return Sender.CONSOLE_NAME;
}
return name;
}
@Override
protected void sendMessage(ServerCommandSource sender, Component message) {
final Locale locale;
if (sender.getEntity() instanceof ServerPlayerEntity) {
String language = ((ServerPlayerEntity) sender.getEntity()).getClientOptions().language();
locale = language == null ? null : TranslationManager.parseLocale(language);
} else {
locale = null;
}
sender.sendFeedback(() -> toNativeText(TranslationManager.render(message, locale)), false);
}
@Override
protected Tristate getPermissionValue(ServerCommandSource commandSource, String node) {
switch (Permissions.getPermissionValue(commandSource, node)) {
case TRUE:
return Tristate.TRUE;
case FALSE:
return Tristate.FALSE;
case DEFAULT:
return Tristate.UNDEFINED;
default:
throw new AssertionError();
}
}
@Override
protected boolean hasPermission(ServerCommandSource commandSource, String node) {
return getPermissionValue(commandSource, node).asBoolean();
}
@Override
protected void performCommand(ServerCommandSource sender, String command) {
sender.getServer().getCommandManager().parseAndExecute(sender, command);
}
@Override
protected boolean isConsole(ServerCommandSource sender) {
CommandOutput output = ((ServerCommandSourceAccessor) sender).getOutput();
return output == sender.getServer() || // Console
output.getClass() == RconCommandOutput.class || // Rcon
(output == CommandOutput.DUMMY && sender.getName().equals("")); // Functions
}
public static Text toNativeText(Component component) {
return TextCodecs.CODEC.decode(
DynamicRegistryManager.EMPTY.getOps(JsonOps.INSTANCE),
GsonComponentSerializer.gson().serializeToTree(component)
).getOrThrow(IllegalArgumentException::new).getFirst();
protected Tristate getPermissionValue(CommandSourceStack commandSource, String node) {
return switch (Permissions.getPermissionValue(commandSource, node)) {
case TRUE -> Tristate.TRUE;
case FALSE -> Tristate.FALSE;
case DEFAULT -> Tristate.UNDEFINED;
};
}
}
@@ -25,7 +25,8 @@
package me.lucko.luckperms.fabric;
import com.mojang.authlib.GameProfile;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsBootstrap;
import me.lucko.luckperms.common.minecraft.MinecraftSchedulerAdapter;
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
import me.lucko.luckperms.common.plugin.logging.Log4jPluginLogger;
@@ -37,8 +38,6 @@ import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.luckperms.api.platform.Platform;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PlayerConfigEntry;
import net.minecraft.server.network.ServerPlayerEntity;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
@@ -46,18 +45,13 @@ import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
/**
* Bootstrap plugin for LuckPerms running on Fabric.
*/
public final class LPFabricBootstrap implements LuckPermsBootstrap, DedicatedServerModInitializer {
public final class LPFabricBootstrap extends MinecraftLuckPermsBootstrap implements LuckPermsBootstrap, DedicatedServerModInitializer {
private static final String MODID = "luckperms";
@@ -104,7 +98,7 @@ public final class LPFabricBootstrap implements LuckPermsBootstrap, DedicatedSer
this.modContainer = FabricLoader.getInstance().getModContainer(MODID)
.orElseThrow(() -> new RuntimeException("Could not get the LuckPerms mod container."));
this.logger = new Log4jPluginLogger(LogManager.getLogger(MODID));
this.schedulerAdapter = new FabricSchedulerAdapter(this);
this.schedulerAdapter = new MinecraftSchedulerAdapter(this);
this.classPathAppender = new FabricClassPathAppender();
this.plugin = new LPFabricPlugin(this);
}
@@ -164,8 +158,7 @@ public final class LPFabricBootstrap implements LuckPermsBootstrap, DedicatedSer
return this.enableLatch;
}
// MinecraftServer singleton getter
@Override
public Optional<MinecraftServer> getServer() {
return Optional.ofNullable(this.server);
}
@@ -204,7 +197,7 @@ public final class LPFabricBootstrap implements LuckPermsBootstrap, DedicatedSer
.map(c -> c.getMetadata().getVersion().getFriendlyString())
.orElse("unknown");
return getServer().map(MinecraftServer::getVersion).orElse("null") + " - fabric-api@" + fabricApiVersion;
return getServer().map(MinecraftServer::getServerVersion).orElse("null") + " - fabric-api@" + fabricApiVersion;
}
@Override
@@ -226,58 +219,6 @@ public final class LPFabricBootstrap implements LuckPermsBootstrap, DedicatedSer
}
}
@Override
public Optional<ServerPlayerEntity> getPlayer(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerManager).map(s -> s.getPlayer(uniqueId));
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
return getServer().map(s -> s.getApiServices().nameToIdCache()).flatMap(c -> c.findByName(username)).map(PlayerConfigEntry::id);
}
@Override
public Optional<String> lookupUsername(UUID uniqueId) {
return getServer().map(s -> s.getApiServices().nameToIdCache()).flatMap(c -> c.getByUuid(uniqueId)).map(PlayerConfigEntry::name);
}
@Override
public int getPlayerCount() {
return getServer().map(MinecraftServer::getCurrentPlayerCount).orElse(0);
}
@Override
public Collection<String> getPlayerList() {
return getServer().map(MinecraftServer::getPlayerManager)
.map(server -> {
List<ServerPlayerEntity> players = server.getPlayerList();
List<String> list = new ArrayList<>(players.size());
for (ServerPlayerEntity player : players) {
list.add(player.getGameProfile().name());
}
return list;
})
.orElse(Collections.emptyList());
}
@Override
public Collection<UUID> getOnlinePlayers() {
return getServer().map(MinecraftServer::getPlayerManager)
.map(server -> {
List<ServerPlayerEntity> players = server.getPlayerList();
List<UUID> list = new ArrayList<>(players.size());
for (ServerPlayerEntity player : players) {
list.add(player.getGameProfile().id());
}
return list;
})
.orElse(Collections.emptyList());
}
@Override
public boolean isPlayerOnline(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerManager).map(s -> s.getPlayer(uniqueId) != null).orElse(false);
}
}
@@ -26,24 +26,16 @@
package me.lucko.luckperms.fabric;
import me.lucko.luckperms.common.api.LuckPermsApiProvider;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.generic.adapter.ConfigurationAdapter;
import me.lucko.luckperms.common.dependencies.Dependency;
import me.lucko.luckperms.common.event.AbstractEventBus;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.messaging.MessagingFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.model.manager.group.StandardGroupManager;
import me.lucko.luckperms.common.model.manager.track.StandardTrackManager;
import me.lucko.luckperms.common.model.manager.user.StandardUserManager;
import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
import me.lucko.luckperms.common.sender.DummyConsoleSender;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftAutoOpListener;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftCommandListUpdater;
import me.lucko.luckperms.fabric.context.FabricContextManager;
import me.lucko.luckperms.fabric.context.FabricPlayerCalculator;
import me.lucko.luckperms.fabric.listeners.FabricAutoOpListener;
import me.lucko.luckperms.fabric.listeners.FabricCommandListUpdater;
import me.lucko.luckperms.fabric.listeners.FabricConnectionListener;
import me.lucko.luckperms.fabric.listeners.FabricOtherListeners;
import me.lucko.luckperms.fabric.listeners.FabricPermissionsApiListener;
@@ -51,36 +43,20 @@ import me.lucko.luckperms.fabric.listeners.FabricPermissionsListener;
import me.lucko.luckperms.fabric.messaging.FabricMessagingFactory;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.OperatorList;
import net.minecraft.server.players.ServerOpList;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
public class LPFabricPlugin extends AbstractLuckPermsPlugin {
private final LPFabricBootstrap bootstrap;
public class LPFabricPlugin extends MinecraftLuckPermsPlugin<LPFabricPlugin, LPFabricBootstrap> {
private FabricConnectionListener connectionListener;
private FabricCommandExecutor commandManager;
private FabricSenderFactory senderFactory;
private FabricContextManager contextManager;
private StandardUserManager userManager;
private StandardGroupManager groupManager;
private StandardTrackManager trackManager;
public LPFabricPlugin(LPFabricBootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public LPFabricBootstrap getBootstrap() {
return this.bootstrap;
super(bootstrap);
}
protected void registerFabricListeners() {
@@ -134,18 +110,6 @@ public class LPFabricPlugin extends AbstractLuckPermsPlugin {
// Too late for Fabric, registered in #registerFabricListeners
}
@Override
protected void setupManagers() {
this.userManager = new StandardUserManager(this);
this.groupManager = new StandardGroupManager(this);
this.trackManager = new StandardTrackManager(this);
}
@Override
protected CalculatorFactory provideCalculatorFactory() {
return new FabricCalculatorFactory(this);
}
@Override
protected void setupContextManager() {
this.contextManager = new FabricContextManager(this);
@@ -173,10 +137,10 @@ public class LPFabricPlugin extends AbstractLuckPermsPlugin {
// remove all operators on startup if they're disabled
if (!getConfiguration().get(ConfigKeys.OPS_ENABLED)) {
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
OperatorList operatorList = server.getPlayerManager().getOpList();
operatorList.values().clear();
ServerOpList opList = server.getPlayerList().getOps();
opList.getEntries().clear();
try {
operatorList.save();
opList.save();
} catch (IOException exception) {
exception.printStackTrace();
}
@@ -185,12 +149,12 @@ public class LPFabricPlugin extends AbstractLuckPermsPlugin {
// register autoop listener
if (getConfiguration().get(ConfigKeys.AUTO_OP)) {
getApiProvider().getEventBus().subscribe(new FabricAutoOpListener(this));
getApiProvider().getEventBus().subscribe(new MinecraftAutoOpListener(this));
}
// register fabric command list updater
if (getConfiguration().get(ConfigKeys.UPDATE_CLIENT_COMMAND_LIST)) {
getApiProvider().getEventBus().subscribe(new FabricCommandListUpdater(this));
getApiProvider().getEventBus().subscribe(new MinecraftCommandListUpdater(this));
}
}
@@ -213,44 +177,4 @@ public class LPFabricPlugin extends AbstractLuckPermsPlugin {
return this.contextManager;
}
@Override
public StandardUserManager getUserManager() {
return this.userManager;
}
@Override
public StandardGroupManager getGroupManager() {
return this.groupManager;
}
@Override
public StandardTrackManager getTrackManager() {
return this.trackManager;
}
@Override
public Optional<QueryOptions> getQueryOptionsForUser(User user) {
return this.bootstrap.getPlayer(user.getUniqueId()).map(player -> this.contextManager.getQueryOptions(player));
}
@Override
public Stream<Sender> getOnlineSenders() {
return Stream.concat(
Stream.of(getConsoleSender()),
this.bootstrap.getServer().map(MinecraftServer::getPlayerManager).map(s -> s.getPlayerList().stream().map(p -> this.senderFactory.wrap(p.getCommandSource()))).orElseGet(Stream::empty)
);
}
@Override
public Sender getConsoleSender() {
return this.bootstrap.getServer()
.map(s -> this.senderFactory.wrap(s.getCommandSource()))
.orElseGet(() -> new DummyConsoleSender(this) {
@Override
public void sendMessage(Component message) {
LPFabricPlugin.this.bootstrap.getPluginLogger().info(PlainTextComponentSerializer.plainText().serialize(TranslationManager.render(message)));
}
});
}
}
@@ -1,50 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.fabric.calculator;
import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.calculator.processor.AbstractPermissionProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import net.luckperms.api.util.Tristate;
/**
* Permission processor which is added to the owner of an Integrated server to
* simply return true if no other processors match.
*/
public class ServerOwnerProcessor extends AbstractPermissionProcessor implements PermissionProcessor {
private static final TristateResult TRUE_RESULT = new TristateResult.Factory(ServerOwnerProcessor.class).result(Tristate.TRUE);
public static final ServerOwnerProcessor INSTANCE = new ServerOwnerProcessor();
private ServerOwnerProcessor() {
}
@Override
public TristateResult hasPermission(String permission) {
return TRUE_RESULT;
}
}
@@ -27,37 +27,35 @@ package me.lucko.luckperms.fabric.context;
import me.lucko.luckperms.common.context.manager.DetachedContextManager;
import me.lucko.luckperms.common.context.manager.QueryOptionsSupplier;
import me.lucko.luckperms.common.minecraft.context.MinecraftContextManager;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.fabric.model.MixinUser;
import net.luckperms.api.query.OptionKey;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Objects;
import java.util.UUID;
public class FabricContextManager extends DetachedContextManager<ServerPlayerEntity, ServerPlayerEntity> {
public static final OptionKey<Boolean> INTEGRATED_SERVER_OWNER = OptionKey.of("integrated_server_owner", Boolean.class);
public class FabricContextManager extends DetachedContextManager<ServerPlayer, ServerPlayer> implements MinecraftContextManager {
public FabricContextManager(LuckPermsPlugin plugin) {
super(plugin, ServerPlayerEntity.class, ServerPlayerEntity.class);
super(plugin, ServerPlayer.class, ServerPlayer.class);
}
@Override
public UUID getUniqueId(ServerPlayerEntity player) {
return player.getUuid();
public UUID getUniqueId(ServerPlayer player) {
return player.getUUID();
}
@Override
public @Nullable QueryOptionsSupplier getQueryOptionsSupplier(ServerPlayerEntity subject) {
public @Nullable QueryOptionsSupplier getQueryOptionsSupplier(ServerPlayer subject) {
Objects.requireNonNull(subject, "subject");
return ((MixinUser) subject).luckperms$getQueryOptionsCache(this);
}
@Override
public void customizeQueryOptions(ServerPlayerEntity subject, QueryOptions.Builder builder) {
if (subject.getEntityWorld().getServer().isHost(subject.getPlayerConfigEntry())) {
public void customizeQueryOptions(ServerPlayer subject, QueryOptions.Builder builder) {
if (subject.level().getServer().isSingleplayerOwner(subject.nameAndId())) {
builder.option(INTEGRATED_SERVER_OWNER, true);
}
}
@@ -25,103 +25,26 @@
package me.lucko.luckperms.fabric.context;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.util.EnumNamer;
import me.lucko.luckperms.common.minecraft.context.MinecraftPlayerCalculator;
import me.lucko.luckperms.fabric.LPFabricPlugin;
import net.fabricmc.fabric.api.entity.event.v1.ServerEntityWorldChangeEvents;
import net.luckperms.api.context.Context;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.ImmutableContextSet;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.world.GameMode;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.jetbrains.annotations.NotNull;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import java.util.Optional;
import java.util.Set;
public class FabricPlayerCalculator implements ContextCalculator<ServerPlayerEntity> {
private static final EnumNamer<GameMode> GAMEMODE_NAMER = new EnumNamer<>(
GameMode.class,
EnumNamer.LOWER_CASE_NAME
);
private final LPFabricPlugin plugin;
private final boolean gamemode;
private final boolean world;
//private final boolean dimensionType;
public class FabricPlayerCalculator extends MinecraftPlayerCalculator {
public FabricPlayerCalculator(LPFabricPlugin plugin, Set<String> disabled) {
this.plugin = plugin;
this.gamemode = !disabled.contains(DefaultContextKeys.GAMEMODE_KEY);
this.world = !disabled.contains(DefaultContextKeys.WORLD_KEY);
//this.dimensionType = !disabled.contains(DefaultContextKeys.DIMENSION_TYPE_KEY);
super(plugin, disabled);
}
public void registerListeners() {
ServerEntityWorldChangeEvents.AFTER_PLAYER_CHANGE_WORLD.register(this::onWorldChange);
}
@Override
public void calculate(@NonNull ServerPlayerEntity target, @NonNull ContextConsumer consumer) {
GameMode mode = target.interactionManager.getGameMode();
if (this.gamemode && mode != null) {
consumer.accept(DefaultContextKeys.GAMEMODE_KEY, GAMEMODE_NAMER.name(mode));
}
// TODO: figure out dimension type context too
ServerWorld world = target.getEntityWorld();
if (this.world) {
this.plugin.getConfiguration().get(ConfigKeys.WORLD_REWRITES).rewriteAndSubmit(getContextKey(world.getRegistryKey().getValue()), consumer);
}
}
@Override
public @NotNull @NonNull ContextSet estimatePotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
if (this.gamemode) {
for (GameMode mode : GameMode.values()) {
builder.add(DefaultContextKeys.GAMEMODE_KEY, GAMEMODE_NAMER.name(mode));
}
}
// TODO: dimension type
Optional<MinecraftServer> server = this.plugin.getBootstrap().getServer();
if (this.world && server.isPresent()) {
Iterable<ServerWorld> worlds = server.get().getWorlds();
for (ServerWorld world : worlds) {
String worldName = getContextKey(world.getRegistryKey().getValue());
if (Context.isValidValue(worldName)) {
builder.add(DefaultContextKeys.WORLD_KEY, worldName);
}
}
}
return builder.build();
}
private static String getContextKey(Identifier key) {
if (key.getNamespace().equals("minecraft")) {
return key.getPath();
}
return key.toString();
}
private void onWorldChange(ServerPlayerEntity player, ServerWorld origin, ServerWorld destination) {
if (this.world) {
this.plugin.getContextManager().invalidateCache(player);
private void onWorldChange(ServerPlayer player, ServerLevel origin, ServerLevel destination) {
if (this.world || this.dimensionType) {
this.plugin.getContextManager().signalContextUpdate(player);
}
}
}
@@ -27,7 +27,7 @@ package me.lucko.luckperms.fabric.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
public interface PreExecuteCommandCallback {
Event<PreExecuteCommandCallback> EVENT = EventFactory.createArrayBacked(PreExecuteCommandCallback.class, listeners -> (source, input) -> {
@@ -39,5 +39,5 @@ public interface PreExecuteCommandCallback {
return true;
});
boolean onPreExecuteCommand(ServerCommandSource source, String input);
boolean onPreExecuteCommand(CommandSourceStack source, String input);
}
@@ -27,17 +27,17 @@ package me.lucko.luckperms.fabric.event;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.command.permission.PermissionPredicate;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.PermissionSet;
public interface SetupPlayerPermissionsEvent {
Event<SetupPlayerPermissionsEvent> EVENT = EventFactory.createArrayBacked(SetupPlayerPermissionsEvent.class, listeners -> (entity, defaultPredicate) -> {
PermissionPredicate predicate = defaultPredicate;
Event<SetupPlayerPermissionsEvent> EVENT = EventFactory.createArrayBacked(SetupPlayerPermissionsEvent.class, listeners -> (entity, defaults) -> {
PermissionSet set = defaults;
for (SetupPlayerPermissionsEvent listener : listeners) {
predicate = listener.onSetupPlayerPermissions(entity, predicate);
set = listener.onSetupPlayerPermissions(entity, set);
}
return predicate;
return set;
});
PermissionPredicate onSetupPlayerPermissions(ServerPlayerEntity entity, PermissionPredicate defaultPredicate);
PermissionSet onSetupPlayerPermissions(ServerPlayer entity, PermissionSet defaults);
}
@@ -1,96 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.fabric.listeners;
import me.lucko.luckperms.common.api.implementation.ApiUser;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.fabric.LPFabricPlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.network.ServerPlayerEntity;
import java.util.Map;
public class FabricAutoOpListener implements LuckPermsEventListener {
private static final String NODE = "luckperms.autoop";
private final LPFabricPlugin plugin;
public FabricAutoOpListener(LPFabricPlugin plugin) {
this.plugin = plugin;
}
@Override
public void bind(EventBus bus) {
bus.subscribe(UserDataRecalculateEvent.class, this::onUserDataRecalculate);
bus.subscribe(ContextUpdateEvent.class, this::onContextUpdate);
}
private void onUserDataRecalculate(UserDataRecalculateEvent e) {
User user = ApiUser.cast(e.getUser());
this.plugin.getBootstrap().getPlayer(user.getUniqueId()).ifPresent(p -> refreshAutoOp(p, false));
}
private void onContextUpdate(ContextUpdateEvent e) {
e.getSubject(ServerPlayerEntity.class).ifPresent(p -> refreshAutoOp(p, true));
}
private void refreshAutoOp(ServerPlayerEntity player, boolean callerIsSync) {
if (!callerIsSync && !this.plugin.getBootstrap().getServer().isPresent()) {
return;
}
User user = this.plugin.getUserManager().getIfLoaded(player.getUuid());
boolean value;
if (user != null) {
QueryOptions queryOptions = this.plugin.getContextManager().getQueryOptions(player);
Map<String, Boolean> permData = user.getCachedData().getPermissionData(queryOptions).getPermissionMap();
value = permData.getOrDefault(NODE, false);
} else {
value = false;
}
if (callerIsSync) {
setOp(player, value);
} else {
this.plugin.getBootstrap().getScheduler().executeSync(() -> setOp(player, value));
}
}
private void setOp(ServerPlayerEntity player, boolean value) {
this.plugin.getBootstrap().getServer().ifPresent(server -> {
if (value) {
server.getPlayerManager().addToOperators(player.getPlayerConfigEntry());
} else {
server.getPlayerManager().removeFromOperators(player.getPlayerConfigEntry());
}
});
}
}
@@ -1,116 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.fabric.listeners;
import com.github.benmanes.caffeine.cache.LoadingCache;
import me.lucko.luckperms.common.api.implementation.ApiGroup;
import me.lucko.luckperms.common.cache.BufferedRequest;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.util.CaffeineFactory;
import me.lucko.luckperms.fabric.LPFabricPlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.group.GroupDataRecalculateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
import net.minecraft.server.network.ServerPlayerEntity;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Calls {@link net.minecraft.server.PlayerManager#sendCommandTree()} when a players permissions change.
*
* TODO: Extract base class for this and BukkitCommandListUpdater
*/
public class FabricCommandListUpdater implements LuckPermsEventListener {
private final LPFabricPlugin plugin;
private final LoadingCache<UUID, SendBuffer> sendingBuffers = CaffeineFactory.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.build(SendBuffer::new);
public FabricCommandListUpdater(LPFabricPlugin plugin) {
this.plugin = plugin;
}
@Override
public void bind(EventBus bus) {
bus.subscribe(UserDataRecalculateEvent.class, this::onUserDataRecalculate);
bus.subscribe(GroupDataRecalculateEvent.class, this::onGroupDataRecalculate);
bus.subscribe(ContextUpdateEvent.class, this::onContextUpdate);
}
private void onUserDataRecalculate(UserDataRecalculateEvent e) {
requestUpdate(e.getUser().getUniqueId());
}
private void onGroupDataRecalculate(GroupDataRecalculateEvent e) {
plugin.getUserManager().getAll().values().stream()
.filter(u -> u.resolveInheritanceTree(u.getQueryOptions())
.contains(ApiGroup.cast(e.getGroup())))
.forEach(u -> requestUpdate(u.getUniqueId()));
}
private void onContextUpdate(ContextUpdateEvent e) {
e.getSubject(ServerPlayerEntity.class).ifPresent(p -> requestUpdate(p.getUuid()));
}
private void requestUpdate(UUID uniqueId) {
if (!this.plugin.getBootstrap().isPlayerOnline(uniqueId)) {
return;
}
// Buffer the request to send a commands update.
this.sendingBuffers.get(uniqueId).request();
}
// Called when the buffer times out.
private void sendUpdate(UUID uniqueId) {
this.plugin.getBootstrap().getScheduler().sync()
.execute(() -> this.plugin.getBootstrap().getPlayer(uniqueId)
.ifPresent(player -> this.plugin.getBootstrap().getServer()
.ifPresent(server -> {
server.getPlayerManager().sendCommandTree(player);
})
)
);
}
private final class SendBuffer extends BufferedRequest<Void> {
private final UUID uniqueId;
SendBuffer(UUID uniqueId) {
super(500, TimeUnit.MILLISECONDS, FabricCommandListUpdater.this.plugin.getBootstrap().getScheduler());
this.uniqueId = uniqueId;
}
@Override
protected Void perform() {
sendUpdate(this.uniqueId);
return null;
}
}
}
@@ -29,11 +29,11 @@ import com.mojang.authlib.GameProfile;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.minecraft.MinecraftSenderFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.plugin.util.AbstractConnectionListener;
import me.lucko.luckperms.fabric.FabricSenderFactory;
import me.lucko.luckperms.fabric.LPFabricPlugin;
import me.lucko.luckperms.fabric.mixin.ServerLoginNetworkHandlerAccessor;
import me.lucko.luckperms.fabric.mixin.ServerLoginPacketListenerImplAccessor;
import me.lucko.luckperms.fabric.model.MixinUser;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerLoginConnectionEvents;
@@ -41,9 +41,9 @@ import net.fabricmc.fabric.api.networking.v1.ServerLoginNetworking.LoginSynchron
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.kyori.adventure.text.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerLoginNetworkHandler;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -62,11 +62,11 @@ public class FabricConnectionListener extends AbstractConnectionListener {
ServerPlayConnectionEvents.DISCONNECT.register(this::onDisconnect);
}
private void onPreLogin(ServerLoginNetworkHandler netHandler, MinecraftServer server, PacketSender packetSender, LoginSynchronizer sync) {
private void onPreLogin(ServerLoginPacketListenerImpl netHandler, MinecraftServer server, PacketSender packetSender, LoginSynchronizer sync) {
/* Called when the player first attempts a connection with the server. */
// Get their profile from the net handler - it should have been initialised by now.
GameProfile profile = ((ServerLoginNetworkHandlerAccessor) netHandler).getGameProfile();
GameProfile profile = ((ServerLoginPacketListenerImplAccessor) netHandler).getAuthenticatedProfile();
UUID uniqueId = profile.id();
String username = profile.name();
@@ -78,7 +78,7 @@ public class FabricConnectionListener extends AbstractConnectionListener {
sync.waitFor(CompletableFuture.runAsync(() -> onPreLoginAsync(netHandler, uniqueId, username), this.plugin.getBootstrap().getScheduler().async()));
}
private void onPreLoginAsync(ServerLoginNetworkHandler netHandler, UUID uniqueId, String username) {
private void onPreLoginAsync(ServerLoginPacketListenerImpl netHandler, UUID uniqueId, String username) {
if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
this.plugin.getLogger().info("Processing pre-login (async phase) for " + uniqueId + " - " + username);
}
@@ -101,26 +101,26 @@ public class FabricConnectionListener extends AbstractConnectionListener {
// deny the connection
Component reason = TranslationManager.render(Message.LOADING_DATABASE_ERROR.build());
netHandler.disconnect(FabricSenderFactory.toNativeText(reason));
netHandler.disconnect(MinecraftSenderFactory.toNativeText(reason));
this.plugin.getEventDispatcher().dispatchPlayerLoginProcess(uniqueId, username, null);
}
}
private void onLogin(ServerPlayNetworkHandler netHandler, PacketSender packetSender, MinecraftServer server) {
final ServerPlayerEntity player = netHandler.player;
private void onLogin(ServerGamePacketListenerImpl netHandler, PacketSender packetSender, MinecraftServer server) {
final ServerPlayer player = netHandler.player;
if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
this.plugin.getLogger().info("Processing login for " + player.getUuid() + " - " + player.getGameProfile().name());
this.plugin.getLogger().info("Processing login for " + player.getUUID() + " - " + player.getGameProfile().name());
}
final User user = this.plugin.getUserManager().getIfLoaded(player.getUuid());
final User user = this.plugin.getUserManager().getIfLoaded(player.getUUID());
/* User instance is null for whatever reason. Could be that it was unloaded between asyncpre and now. */
if (user == null) {
this.plugin.getLogger().warn("User " + player.getUuid() + " - " + player.getGameProfile().id() +
this.plugin.getLogger().warn("User " + player.getUUID() + " - " + player.getGameProfile().id() +
" doesn't currently have data pre-loaded - denying login.");
Component reason = TranslationManager.render(Message.LOADING_STATE_ERROR.build());
netHandler.disconnect(FabricSenderFactory.toNativeText(reason));
netHandler.disconnect(MinecraftSenderFactory.toNativeText(reason));
return;
}
@@ -130,9 +130,9 @@ public class FabricConnectionListener extends AbstractConnectionListener {
this.plugin.getContextManager().signalContextUpdate(player);
}
private void onDisconnect(ServerPlayNetworkHandler netHandler, MinecraftServer server) {
private void onDisconnect(ServerGamePacketListenerImpl netHandler, MinecraftServer server) {
if (!server.isStopped()) {
handleDisconnect(netHandler.player.getUuid());
handleDisconnect(netHandler.player.getUUID());
}
}
@@ -29,14 +29,14 @@ import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.fabric.LPFabricPlugin;
import me.lucko.luckperms.fabric.event.PreExecuteCommandCallback;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import java.util.regex.Pattern;
public class FabricOtherListeners {
private static final Pattern OP_COMMAND_PATTERN = Pattern.compile("^/?(deop|op)( .*)?$");
private LPFabricPlugin plugin;
private final LPFabricPlugin plugin;
public FabricOtherListeners(LPFabricPlugin plugin) {
this.plugin = plugin;
@@ -46,7 +46,7 @@ public class FabricOtherListeners {
PreExecuteCommandCallback.EVENT.register(this::onPreExecuteCommand);
}
private boolean onPreExecuteCommand(ServerCommandSource source, String input) {
private boolean onPreExecuteCommand(CommandSourceStack source, String input) {
if (input.isEmpty()) {
return true;
}
@@ -41,10 +41,10 @@ import me.lucko.luckperms.fabric.LPFabricPlugin;
import me.lucko.luckperms.fabric.model.MixinUser;
import net.fabricmc.fabric.api.util.TriState;
import net.luckperms.api.util.Tristate;
import net.minecraft.command.CommandSource;
import net.minecraft.entity.Entity;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Optional;
@@ -68,21 +68,21 @@ public class FabricPermissionsApiListener {
OfflineOptionRequestEvent.EVENT.register(this::onOfflineOptionRequest);
}
private @NonNull TriState onPermissionCheck(CommandSource source, String permission) {
if (source instanceof ServerCommandSource) {
Entity entity = ((ServerCommandSource) source).getEntity();
if (entity instanceof ServerPlayerEntity) {
return playerPermissionCheck((ServerPlayerEntity) entity, permission);
private @NonNull TriState onPermissionCheck(SharedSuggestionProvider source, String permission) {
if (source instanceof CommandSourceStack) {
Entity entity = ((CommandSourceStack) source).getEntity();
if (entity instanceof ServerPlayer) {
return playerPermissionCheck((ServerPlayer) entity, permission);
}
}
return otherPermissionCheck(source, permission);
}
private @NonNull Optional<String> onOptionRequest(CommandSource source, String key) {
if (source instanceof ServerCommandSource) {
Entity entity = ((ServerCommandSource) source).getEntity();
if (entity instanceof ServerPlayerEntity) {
return playerGetOption((ServerPlayerEntity) entity, key);
private @NonNull Optional<String> onOptionRequest(SharedSuggestionProvider source, String key) {
if (source instanceof CommandSourceStack) {
Entity entity = ((CommandSourceStack) source).getEntity();
if (entity instanceof ServerPlayer) {
return playerGetOption((ServerPlayer) entity, key);
}
}
return otherGetOption(source, key);
@@ -110,13 +110,13 @@ public class FabricPermissionsApiListener {
return this.plugin.getStorage().loadUser(uuid, null);
}
private TriState playerPermissionCheck(ServerPlayerEntity player, String permission) {
private TriState playerPermissionCheck(ServerPlayer player, String permission) {
return fabricTristate(((MixinUser) player).luckperms$hasPermission(permission));
}
private TriState otherPermissionCheck(CommandSource source, String permission) {
if (source instanceof ServerCommandSource) {
String name = ((ServerCommandSource) source).getName();
private TriState otherPermissionCheck(SharedSuggestionProvider source, String permission) {
if (source instanceof CommandSourceStack) {
String name = ((CommandSourceStack) source).getTextName();
VerboseCheckTarget target = VerboseCheckTarget.internal(name);
this.plugin.getVerboseHandler().offerPermissionCheckEvent(CheckOrigin.PLATFORM_API_HAS_PERMISSION, target, QueryOptionsImpl.DEFAULT_CONTEXTUAL, permission, TristateResult.UNDEFINED);
@@ -126,13 +126,13 @@ public class FabricPermissionsApiListener {
return TriState.DEFAULT;
}
private Optional<String> playerGetOption(ServerPlayerEntity player, String key) {
private Optional<String> playerGetOption(ServerPlayer player, String key) {
return Optional.ofNullable(((MixinUser) player).luckperms$getOption(key));
}
private Optional<String> otherGetOption(CommandSource source, String key) {
if (source instanceof ServerCommandSource) {
String name = ((ServerCommandSource) source).getName();
private Optional<String> otherGetOption(SharedSuggestionProvider source, String key) {
if (source instanceof CommandSourceStack) {
String name = ((CommandSourceStack) source).getTextName();
VerboseCheckTarget target = VerboseCheckTarget.internal(name);
this.plugin.getVerboseHandler().offerMetaCheckEvent(CheckOrigin.PLATFORM_API, target, QueryOptionsImpl.DEFAULT_CONTEXTUAL, key, StringResult.nullResult());
@@ -28,10 +28,10 @@ package me.lucko.luckperms.fabric.listeners;
import me.lucko.luckperms.fabric.event.SetupPlayerPermissionsEvent;
import me.lucko.luckperms.fabric.model.MixinUser;
import net.luckperms.api.util.Tristate;
import net.minecraft.command.permission.Permission;
import net.minecraft.command.permission.PermissionPredicate;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.Permission;
import net.minecraft.server.permissions.PermissionSet;
/**
* Listener to route permission checks made via Minecraft's native permission predicate to LuckPerms.
@@ -42,15 +42,15 @@ public class FabricPermissionsListener {
SetupPlayerPermissionsEvent.EVENT.register(this::onSetupPlayerPermissions);
}
private PermissionPredicate onSetupPlayerPermissions(ServerPlayerEntity entity, PermissionPredicate predicate) {
return new LuckPermsPermissionPredicate(entity, predicate);
private PermissionSet onSetupPlayerPermissions(ServerPlayer entity, PermissionSet defaults) {
return new LuckPermsPermissionSet(entity, defaults);
}
private static final class LuckPermsPermissionPredicate implements PermissionPredicate {
private final ServerPlayerEntity player;
private final PermissionPredicate delegate;
private static final class LuckPermsPermissionSet implements PermissionSet {
private final ServerPlayer player;
private final PermissionSet delegate;
LuckPermsPermissionPredicate(ServerPlayerEntity player, PermissionPredicate delegate) {
LuckPermsPermissionSet(ServerPlayer player, PermissionSet delegate) {
this.player = player;
this.delegate = delegate;
}
@@ -32,20 +32,20 @@ import me.lucko.luckperms.fabric.LPFabricPlugin;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.luckperms.api.messenger.IncomingMessageConsumer;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.server.level.ServerPlayer;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class PluginMessageMessenger extends AbstractPluginMessageMessenger implements ServerPlayNetworking.PlayPayloadHandler<PluginMessageMessenger.PluginMessagePayload> {
private static final Identifier CHANNEL = Identifier.of(AbstractPluginMessageMessenger.CHANNEL);
private static final Identifier CHANNEL = Identifier.parse(AbstractPluginMessageMessenger.CHANNEL);
private final LPFabricPlugin plugin;
@@ -55,9 +55,9 @@ public class PluginMessageMessenger extends AbstractPluginMessageMessenger imple
}
public void init() {
PayloadTypeRegistry.playS2C().register(PluginMessagePayload.ID, PluginMessagePayload.CODEC);
PayloadTypeRegistry.playC2S().register(PluginMessagePayload.ID, PluginMessagePayload.CODEC);
ServerPlayNetworking.registerGlobalReceiver(PluginMessagePayload.ID, this);
PayloadTypeRegistry.playS2C().register(PluginMessagePayload.TYPE, PluginMessagePayload.CODEC);
PayloadTypeRegistry.playC2S().register(PluginMessagePayload.TYPE, PluginMessagePayload.CODEC);
ServerPlayNetworking.registerGlobalReceiver(PluginMessagePayload.TYPE, this);
}
@Override
@@ -74,8 +74,8 @@ public class PluginMessageMessenger extends AbstractPluginMessageMessenger imple
return;
}
Collection<ServerPlayerEntity> players = server.getPlayerManager().getPlayerList();
ServerPlayerEntity p = Iterables.getFirst(players, null);
Collection<ServerPlayer> players = server.getPlayerList().getPlayers();
ServerPlayer p = Iterables.getFirst(players, null);
if (p == null) {
return;
}
@@ -95,9 +95,9 @@ public class PluginMessageMessenger extends AbstractPluginMessageMessenger imple
handleIncomingMessage(payload.data);
}
public static class PluginMessagePayload implements CustomPayload {
public static final CustomPayload.Id<PluginMessagePayload> ID = new CustomPayload.Id<>(CHANNEL);
public static final PacketCodec<RegistryByteBuf, PluginMessagePayload> CODEC = PacketCodec.of(PluginMessagePayload::write, PluginMessagePayload::new).cast();
public static class PluginMessagePayload implements CustomPacketPayload {
public static final CustomPacketPayload.Type<PluginMessagePayload> TYPE = new CustomPacketPayload.Type<>(CHANNEL);
public static final StreamCodec<RegistryFriendlyByteBuf, PluginMessagePayload> CODEC = StreamCodec.ofMember(PluginMessagePayload::write, PluginMessagePayload::new).cast();
private final byte[] data;
@@ -105,18 +105,18 @@ public class PluginMessageMessenger extends AbstractPluginMessageMessenger imple
this.data = data;
}
private PluginMessagePayload(PacketByteBuf buf) {
private PluginMessagePayload(FriendlyByteBuf buf) {
this.data = new byte[buf.readableBytes()];
buf.readBytes(this.data);
}
private void write(PacketByteBuf buf) {
private void write(FriendlyByteBuf buf) {
buf.writeBytes(this.data);
}
@Override
public Id<PluginMessagePayload> getId() {
return ID;
public Type<PluginMessagePayload> type() {
return TYPE;
}
}
}
@@ -25,18 +25,18 @@
package me.lucko.luckperms.fabric.mixin;
import net.minecraft.server.command.CommandOutput;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
/**
* Accessor mixin to provide access to the underlying {@link CommandOutput}
* Accessor mixin to provide access to the underlying {@link CommandSource}
*/
@Mixin(ServerCommandSource.class)
public interface ServerCommandSourceAccessor {
@Mixin(CommandSourceStack.class)
public interface CommandSourceStackAccessor {
@Accessor("output")
CommandOutput getOutput();
@Accessor("source")
CommandSource getSource();
}
@@ -27,17 +27,17 @@ package me.lucko.luckperms.fabric.mixin;
import com.mojang.brigadier.ParseResults;
import me.lucko.luckperms.fabric.event.PreExecuteCommandCallback;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CommandManager.class)
public class CommandManagerMixin {
@Inject(at = @At("HEAD"), method = "execute", cancellable = true)
private void commandExecuteCallback(ParseResults<ServerCommandSource> parseResults, String command, CallbackInfo ci) {
@Mixin(Commands.class)
public class CommandsMixin {
@Inject(at = @At("HEAD"), method = "performCommand", cancellable = true)
private void commandExecuteCallback(ParseResults<CommandSourceStack> parseResults, String command, CallbackInfo ci) {
if (!PreExecuteCommandCallback.EVENT.invoker().onPreExecuteCommand(parseResults.getContext().getSource(), command)) {
ci.cancel();
}
@@ -26,7 +26,7 @@
package me.lucko.luckperms.fabric.mixin;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.network.ServerLoginNetworkHandler;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@@ -34,10 +34,10 @@ import org.spongepowered.asm.mixin.gen.Accessor;
* Accessor mixin to provide access to the underlying {@link GameProfile} during the server
* login handling.
*/
@Mixin(ServerLoginNetworkHandler.class)
public interface ServerLoginNetworkHandlerAccessor {
@Mixin(ServerLoginPacketListenerImpl.class)
public interface ServerLoginPacketListenerImplAccessor {
@Accessor("profile")
GameProfile getGameProfile();
@Accessor("authenticatedProfile")
GameProfile getAuthenticatedProfile();
}
@@ -35,8 +35,8 @@ import me.lucko.luckperms.fabric.event.SetupPlayerPermissionsEvent;
import me.lucko.luckperms.fabric.model.MixinUser;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.command.permission.PermissionPredicate;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.PermissionSet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
@@ -45,10 +45,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* Mixin into {@link ServerPlayerEntity} to store LP caches and implement {@link MixinUser}.
* Mixin into {@link ServerPlayer} to store LP caches and implement {@link MixinUser}.
*/
@Mixin(ServerPlayerEntity.class)
public abstract class ServerPlayerEntityMixin implements MixinUser {
@Mixin(ServerPlayer.class)
public abstract class ServerPlayerMixin implements MixinUser {
/** Cache a reference to the LP {@link User} instance loaded for this player */
@Unique
@@ -69,7 +69,7 @@ public abstract class ServerPlayerEntityMixin implements MixinUser {
@Override
public QueryOptionsSupplier luckperms$getQueryOptionsCache(FabricContextManager contextManager) {
if (this.luckperms$queryOptions == null) {
this.luckperms$queryOptions = contextManager.createQueryOptionsSupplier((ServerPlayerEntity) (Object) this);
this.luckperms$queryOptions = contextManager.createQueryOptionsSupplier((ServerPlayer) (Object) this);
}
return this.luckperms$queryOptions;
}
@@ -150,20 +150,20 @@ public abstract class ServerPlayerEntityMixin implements MixinUser {
return cache.getMetaOrChatMetaValue(key, CheckOrigin.PLATFORM_API);
}
@Inject(at = @At("TAIL"), method = "copyFrom")
private void luckperms$copyFrom(ServerPlayerEntity oldPlayer, boolean alive, CallbackInfo ci) {
@Inject(at = @At("TAIL"), method = "restoreFrom")
private void luckperms$restoreFrom(ServerPlayer oldPlayer, boolean alive, CallbackInfo ci) {
MixinUser oldMixin = (MixinUser) oldPlayer;
luckperms$initializePermissions(oldMixin.luckperms$getUser());
}
@Inject(at = @At("RETURN"), method = "getPermissions", cancellable = true)
private void luckperms$getPermissions(CallbackInfoReturnable<PermissionPredicate> cir) {
ServerPlayerEntity entity = (ServerPlayerEntity) (Object) this;
PermissionPredicate predicate = cir.getReturnValue();
@Inject(at = @At("RETURN"), method = "permissions", cancellable = true)
private void luckperms$permissions(CallbackInfoReturnable<PermissionSet> cir) {
ServerPlayer entity = (ServerPlayer) (Object) this;
PermissionSet set = cir.getReturnValue();
PermissionPredicate newPredicate = SetupPlayerPermissionsEvent.EVENT.invoker().onSetupPlayerPermissions(entity, predicate);
if (newPredicate != predicate) {
cir.setReturnValue(newPredicate);
PermissionSet newSet = SetupPlayerPermissionsEvent.EVENT.invoker().onSetupPlayerPermissions(entity, set);
if (newSet != set) {
cir.setReturnValue(newSet);
}
}
}
@@ -30,11 +30,10 @@ import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.fabric.context.FabricContextManager;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.level.ServerPlayer;
/**
* Mixin interface for {@link ServerPlayerEntity} implementing {@link User} related
* caches and functions.
* Mixin interface for {@link ServerPlayer} implementing {@link User} related caches and functions.
*/
public interface MixinUser {
@@ -3,10 +3,10 @@
"package": "me.lucko.luckperms.fabric.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [
"CommandManagerMixin",
"ServerCommandSourceAccessor",
"ServerLoginNetworkHandlerAccessor",
"ServerPlayerEntityMixin"
"CommandsMixin",
"CommandSourceStackAccessor",
"ServerLoginPacketListenerImplAccessor",
"ServerPlayerMixin"
],
"client": [
],
+1
View File
@@ -20,6 +20,7 @@ dependencies {
minecraft "net.minecraftforge:forge:${minecraftVersion}-${forgeVersion}"
annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.12'
implementation project(':common')
implementation project(':common:minecraft')
compileOnly project(':common:loader-utils')
}
@@ -25,48 +25,19 @@
package me.lucko.luckperms.forge;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.command.BrigadierCommandExecutor;
import me.lucko.luckperms.common.sender.Sender;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import net.minecraft.server.permissions.Permission;
import net.minecraft.server.permissions.PermissionLevel;
import me.lucko.luckperms.common.minecraft.command.MinecraftCommandExecutor;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.server.ServerStartedEvent;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import java.util.List;
import java.util.ListIterator;
public class ForgeCommandExecutor extends BrigadierCommandExecutor<CommandSourceStack> {
private final LPForgePlugin plugin;
public class ForgeCommandExecutor extends MinecraftCommandExecutor {
public ForgeCommandExecutor(LPForgePlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@SubscribeEvent
public void onRegisterCommands(RegisterCommandsEvent event) {
for (String alias : COMMAND_ALIASES) {
LiteralCommandNode<CommandSourceStack> command = Commands.literal(alias).executes(this).build();
ArgumentCommandNode<CommandSourceStack, String> argument = Commands.argument("args", StringArgumentType.greedyString())
.suggests(this)
.executes(this)
.build();
command.addChild(argument);
event.getDispatcher().getRoot().addChild(command);
}
register(event.getDispatcher());
}
// not used - workaround for the idiotic Forge limitation that requires listeners using the @SubscribeEvent annotation to have at least two listener methods
@@ -74,52 +45,4 @@ public class ForgeCommandExecutor extends BrigadierCommandExecutor<CommandSource
public void onServerStarted(ServerStartedEvent event) {
}
@Override
public Sender getSender(CommandSourceStack source) {
return this.plugin.getSenderFactory().wrap(source);
}
@Override
public List<String> resolveSelectors(CommandSourceStack source, List<String> args) {
// usage of @ selectors requires at least level 2 permission
CommandSourceStack atAllowedSource = ensureSourceCanUseSelectors(source);
for (ListIterator<String> it = args.listIterator(); it.hasNext(); ) {
String arg = it.next();
if (arg.isEmpty() || arg.charAt(0) != '@') {
continue;
}
List<ServerPlayer> matchedPlayers;
try {
matchedPlayers = EntityArgument.entities().parse(new StringReader(arg)).findPlayers(atAllowedSource);
} catch (CommandSyntaxException e) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args, e);
continue;
}
if (matchedPlayers.isEmpty()) {
continue;
}
if (matchedPlayers.size() > 1) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args +
": ambiguous result (more than one player matched) - " + matchedPlayers);
continue;
}
ServerPlayer player = matchedPlayers.get(0);
it.set(player.getStringUUID());
}
return args;
}
private static CommandSourceStack ensureSourceCanUseSelectors(CommandSourceStack source) {
if (source.permissions().hasPermission(new Permission.HasCommandLevel(PermissionLevel.GAMEMASTERS))) {
return source;
}
return source.withMaximumPermission(LevelBasedPermissionSet.GAMEMASTER);
}
}
@@ -25,58 +25,26 @@
package me.lucko.luckperms.forge;
import com.mojang.brigadier.ParseResults;
import com.mojang.serialization.JsonOps;
import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.minecraft.MinecraftSenderFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.query.QueryOptionsImpl;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.sender.SenderFactory;
import me.lucko.luckperms.common.verbose.VerboseCheckTarget;
import me.lucko.luckperms.common.verbose.event.CheckOrigin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.rcon.RconConsoleSource;
import net.minecraft.world.entity.player.Player;
import java.util.Locale;
import java.util.UUID;
public class ForgeSenderFactory extends SenderFactory<LPForgePlugin, CommandSourceStack> {
public class ForgeSenderFactory extends MinecraftSenderFactory<LPForgePlugin> {
public ForgeSenderFactory(LPForgePlugin plugin) {
super(plugin);
}
@Override
protected UUID getUniqueId(CommandSourceStack commandSource) {
if (commandSource.getEntity() instanceof Player) {
return commandSource.getEntity().getUUID();
}
return Sender.CONSOLE_UUID;
}
@Override
protected String getName(CommandSourceStack commandSource) {
if (commandSource.getEntity() instanceof Player) {
return commandSource.getTextName();
}
return Sender.CONSOLE_NAME;
}
@Override
protected void sendMessage(CommandSourceStack sender, Component message) {
Locale locale = sender.getEntity() instanceof ServerPlayer player
? TranslationManager.parseLocale(player.getLanguage())
: null;
sender.sendSuccess(() -> toNativeText(TranslationManager.render(message, locale)), false);
protected CommandSource getSource(CommandSourceStack sender) {
return sender.source;
}
@Override
@@ -96,31 +64,4 @@ public class ForgeSenderFactory extends SenderFactory<LPForgePlugin, CommandSour
getPlugin().getPermissionRegistry().offer(node);
return Tristate.UNDEFINED;
}
@Override
protected boolean hasPermission(CommandSourceStack commandSource, String node) {
return getPermissionValue(commandSource, node).asBoolean();
}
@Override
protected void performCommand(CommandSourceStack sender, String command) {
ParseResults<CommandSourceStack> results = sender.getServer().getCommands().getDispatcher().parse(command, sender);
sender.getServer().getCommands().performCommand(results, command);
}
@Override
protected boolean isConsole(CommandSourceStack sender) {
CommandSource output = sender.source;
return output == sender.getServer() || // Console
output.getClass() == RconConsoleSource.class || // Rcon
(output == CommandSource.NULL && sender.getTextName().equals("")); // Functions
}
public static net.minecraft.network.chat.Component toNativeText(Component component) {
return ComponentSerialization.CODEC.decode(
RegistryAccess.EMPTY.createSerializationContext(JsonOps.INSTANCE),
GsonComponentSerializer.gson().serializeToTree(component)
).getOrThrow(IllegalArgumentException::new).getFirst();
}
}
@@ -25,8 +25,9 @@
package me.lucko.luckperms.forge;
import com.mojang.authlib.GameProfile;
import me.lucko.luckperms.common.loader.LoaderBootstrap;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsBootstrap;
import me.lucko.luckperms.common.minecraft.MinecraftSchedulerAdapter;
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
@@ -36,9 +37,6 @@ import me.lucko.luckperms.common.plugin.logging.PluginLogger;
import me.lucko.luckperms.common.plugin.scheduler.SchedulerAdapter;
import net.luckperms.api.platform.Platform;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.NameAndId;
import net.minecraft.server.players.PlayerList;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.eventbus.api.bus.BusGroup;
@@ -57,17 +55,15 @@ import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;
/**
* Bootstrap plugin for LuckPerms running on Forge.
*/
public final class LPForgeBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
public final class LPForgeBootstrap extends MinecraftLuckPermsBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
public static final String ID = "luckperms";
/**
@@ -117,7 +113,7 @@ public final class LPForgeBootstrap implements LuckPermsBootstrap, LoaderBootstr
public LPForgeBootstrap(Supplier<ModContainer> loader) {
this.loader = loader;
this.logger = new Log4jPluginLogger(LogManager.getLogger(LPForgeBootstrap.ID));
this.schedulerAdapter = new ForgeSchedulerAdapter(this);
this.schedulerAdapter = new MinecraftSchedulerAdapter(this);
this.classPathAppender = new JarInJarClassPathAppender(getClass().getClassLoader());
this.plugin = new LPForgePlugin(this);
}
@@ -199,8 +195,7 @@ public final class LPForgeBootstrap implements LuckPermsBootstrap, LoaderBootstr
return this.enableLatch;
}
// MinecraftServer singleton getter
@Override
public Optional<MinecraftServer> getServer() {
return Optional.ofNullable(this.server);
}
@@ -248,51 +243,4 @@ public final class LPForgeBootstrap implements LuckPermsBootstrap, LoaderBootstr
return FMLPaths.CONFIGDIR.get().resolve(LPForgeBootstrap.ID).toAbsolutePath();
}
@Override
public Optional<ServerPlayer> getPlayer(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList).map(playerList -> playerList.getPlayer(uniqueId));
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
return getServer().map(s -> s.services().nameToIdCache()).flatMap(profileCache -> profileCache.get(username)).map(NameAndId::id);
}
@Override
public Optional<String> lookupUsername(UUID uniqueId) {
return getServer().map(s -> s.services().nameToIdCache()).flatMap(profileCache -> profileCache.get(uniqueId)).map(NameAndId::name);
}
@Override
public int getPlayerCount() {
return getServer().map(MinecraftServer::getPlayerCount).orElse(0);
}
@Override
public Collection<String> getPlayerList() {
return getServer().map(MinecraftServer::getPlayerList).map(PlayerList::getPlayers).map(players -> {
List<String> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().name());
}
return list;
}).orElse(Collections.emptyList());
}
@Override
public Collection<UUID> getOnlinePlayers() {
return getServer().map(MinecraftServer::getPlayerList).map(PlayerList::getPlayers).map(players -> {
List<UUID> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().id());
}
return list;
}).orElse(Collections.emptyList());
}
@Override
public boolean isPlayerOnline(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList).map(playerList -> playerList.getPlayer(uniqueId)).isPresent();
}
}
@@ -26,63 +26,37 @@
package me.lucko.luckperms.forge;
import me.lucko.luckperms.common.api.LuckPermsApiProvider;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.generic.adapter.ConfigurationAdapter;
import me.lucko.luckperms.common.dependencies.Dependency;
import me.lucko.luckperms.common.event.AbstractEventBus;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.messaging.MessagingFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.model.manager.group.StandardGroupManager;
import me.lucko.luckperms.common.model.manager.track.StandardTrackManager;
import me.lucko.luckperms.common.model.manager.user.StandardUserManager;
import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
import me.lucko.luckperms.common.sender.DummyConsoleSender;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.forge.calculator.ForgeCalculatorFactory;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftAutoOpListener;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftCommandListUpdater;
import me.lucko.luckperms.forge.context.ForgeContextManager;
import me.lucko.luckperms.forge.context.ForgePlayerCalculator;
import me.lucko.luckperms.forge.listeners.ForgeAutoOpListener;
import me.lucko.luckperms.forge.listeners.ForgeCommandListUpdater;
import me.lucko.luckperms.forge.listeners.ForgeConnectionListener;
import me.lucko.luckperms.forge.listeners.ForgePlatformListener;
import me.lucko.luckperms.forge.messaging.ForgeMessagingFactory;
import me.lucko.luckperms.forge.messaging.PluginMessageMessenger;
import me.lucko.luckperms.forge.service.ForgePermissionHandlerListener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.players.PlayerList;
import net.minecraftforge.fml.ModContainer;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
/**
* LuckPerms implementation for Forge.
*/
public class LPForgePlugin extends AbstractLuckPermsPlugin {
private final LPForgeBootstrap bootstrap;
public class LPForgePlugin extends MinecraftLuckPermsPlugin<LPForgePlugin, LPForgeBootstrap> {
private ForgeSenderFactory senderFactory;
private ForgeConnectionListener connectionListener;
private ForgeCommandExecutor commandManager;
private StandardUserManager userManager;
private StandardGroupManager groupManager;
private StandardTrackManager trackManager;
private ForgeContextManager contextManager;
public LPForgePlugin(LPForgeBootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public LPForgeBootstrap getBootstrap() {
return this.bootstrap;
super(bootstrap);
}
protected void registerEarlyListeners() {
@@ -137,18 +111,6 @@ public class LPForgePlugin extends AbstractLuckPermsPlugin {
// Too late for Forge, registered in #registerEarlyListeners
}
@Override
protected void setupManagers() {
this.userManager = new StandardUserManager(this);
this.groupManager = new StandardGroupManager(this);
this.trackManager = new StandardTrackManager(this);
}
@Override
protected CalculatorFactory provideCalculatorFactory() {
return new ForgeCalculatorFactory(this);
}
@Override
protected void setupContextManager() {
this.contextManager = new ForgeContextManager(this);
@@ -175,43 +137,15 @@ public class LPForgePlugin extends AbstractLuckPermsPlugin {
protected void performFinalSetup() {
// register autoop listener
if (getConfiguration().get(ConfigKeys.AUTO_OP)) {
getApiProvider().getEventBus().subscribe(new ForgeAutoOpListener(this));
getApiProvider().getEventBus().subscribe(new MinecraftAutoOpListener(this));
}
// register forge command list updater
if (getConfiguration().get(ConfigKeys.UPDATE_CLIENT_COMMAND_LIST)) {
getApiProvider().getEventBus().subscribe(new ForgeCommandListUpdater(this));
getApiProvider().getEventBus().subscribe(new MinecraftCommandListUpdater(this));
}
}
@Override
public Optional<QueryOptions> getQueryOptionsForUser(User user) {
return this.bootstrap.getPlayer(user.getUniqueId()).map(player -> this.contextManager.getQueryOptions(player));
}
@Override
public Stream<Sender> getOnlineSenders() {
return Stream.concat(
Stream.of(getConsoleSender()),
this.bootstrap.getServer()
.map(MinecraftServer::getPlayerList)
.map(PlayerList::getPlayers)
.map(players -> players.stream().map(player -> this.senderFactory.wrap(player.createCommandSourceStack()))).orElseGet(Stream::empty)
);
}
@Override
public Sender getConsoleSender() {
return this.bootstrap.getServer()
.map(server -> this.senderFactory.wrap(server.createCommandSourceStack()))
.orElseGet(() -> new DummyConsoleSender(this) {
@Override
public void sendMessage(Component message) {
LPForgePlugin.this.bootstrap.getPluginLogger().info(PlainTextComponentSerializer.plainText().serialize(TranslationManager.render(message)));
}
});
}
public ForgeSenderFactory getSenderFactory() {
return this.senderFactory;
}
@@ -226,21 +160,6 @@ public class LPForgePlugin extends AbstractLuckPermsPlugin {
return this.commandManager;
}
@Override
public StandardUserManager getUserManager() {
return this.userManager;
}
@Override
public StandardGroupManager getGroupManager() {
return this.groupManager;
}
@Override
public StandardTrackManager getTrackManager() {
return this.trackManager;
}
@Override
public ForgeContextManager getContextManager() {
return this.contextManager;
@@ -1,51 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.forge.calculator;
import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.calculator.processor.AbstractPermissionProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import net.luckperms.api.util.Tristate;
/**
* Permission processor which is added to the owner of an Integrated server to
* simply return true if no other processors match.
*/
public class ServerOwnerProcessor extends AbstractPermissionProcessor implements PermissionProcessor {
private static final TristateResult TRUE_RESULT = new TristateResult.Factory(ServerOwnerProcessor.class).result(Tristate.TRUE);
public static final ServerOwnerProcessor INSTANCE = new ServerOwnerProcessor();
private ServerOwnerProcessor() {
}
@Override
public TristateResult hasPermission(String permission) {
return TRUE_RESULT;
}
}
@@ -26,16 +26,14 @@
package me.lucko.luckperms.forge.context;
import me.lucko.luckperms.common.context.manager.SimpleContextManager;
import me.lucko.luckperms.common.minecraft.context.MinecraftContextManager;
import me.lucko.luckperms.forge.LPForgePlugin;
import net.luckperms.api.query.OptionKey;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.level.ServerPlayer;
import java.util.UUID;
public class ForgeContextManager extends SimpleContextManager<ServerPlayer, ServerPlayer> {
public static final OptionKey<Boolean> INTEGRATED_SERVER_OWNER = OptionKey.of("integrated_server_owner", Boolean.class);
public class ForgeContextManager extends SimpleContextManager<ServerPlayer, ServerPlayer> implements MinecraftContextManager {
public ForgeContextManager(LPForgePlugin plugin) {
super(plugin, ServerPlayer.class, ServerPlayer.class);
}
@@ -47,7 +45,7 @@ public class ForgeContextManager extends SimpleContextManager<ServerPlayer, Serv
@Override
public void customizeQueryOptions(ServerPlayer subject, QueryOptions.Builder builder) {
if (subject.level().getServer() != null && subject.level().getServer().isSingleplayerOwner(subject.nameAndId())) {
if (subject.level().getServer().isSingleplayerOwner(subject.nameAndId())) {
builder.option(INTEGRATED_SERVER_OWNER, true);
}
}
@@ -25,114 +25,31 @@
package me.lucko.luckperms.forge.context;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.minecraft.context.MinecraftPlayerCalculator;
import me.lucko.luckperms.forge.LPForgePlugin;
import net.luckperms.api.context.Context;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.ImmutableContextSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Set;
public class ForgePlayerCalculator implements ContextCalculator<ServerPlayer> {
private final LPForgePlugin plugin;
private final boolean gamemode;
private final boolean world;
private final boolean dimensionType;
public class ForgePlayerCalculator extends MinecraftPlayerCalculator {
public ForgePlayerCalculator(LPForgePlugin plugin, Set<String> disabled) {
this.plugin = plugin;
this.gamemode = !disabled.contains(DefaultContextKeys.GAMEMODE_KEY);
this.world = !disabled.contains(DefaultContextKeys.WORLD_KEY);
this.dimensionType = !disabled.contains(DefaultContextKeys.DIMENSION_TYPE_KEY);
}
@Override
public void calculate(@NonNull ServerPlayer target, @NonNull ContextConsumer consumer) {
ServerLevel level = target.level();
if (this.dimensionType) {
consumer.accept(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(level.dimension().identifier()));
}
if (this.world) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
this.plugin.getConfiguration().get(ConfigKeys.WORLD_REWRITES).rewriteAndSubmit(levelData.getLevelName(), consumer);
}
if (this.gamemode) {
GameType gameMode = target.gameMode.getGameModeForPlayer();
consumer.accept(DefaultContextKeys.GAMEMODE_KEY, gameMode.getName());
}
}
@Override
public @NonNull ContextSet estimatePotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
if (this.gamemode) {
for (GameType gameType : GameType.values()) {
builder.add(DefaultContextKeys.GAMEMODE_KEY, gameType.getName());
}
}
MinecraftServer server = this.plugin.getBootstrap().getServer().orElse(null);
if (this.dimensionType && server != null) {
server.registryAccess().lookup(Registries.DIMENSION_TYPE).ifPresent(registry -> {
for (Identifier id : registry.keySet()) {
builder.add(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(id));
}
});
}
if (this.world && server != null) {
for (ServerLevel level : server.getAllLevels()) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
if (Context.isValidValue(levelData.getLevelName())) {
builder.add(DefaultContextKeys.WORLD_KEY, levelData.getLevelName());
}
}
}
return builder.build();
}
private static String getContextKey(Identifier key) {
if (key.getNamespace().equals("minecraft")) {
return key.getPath();
}
return key.toString();
super(plugin, disabled);
}
@SubscribeEvent
public void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
if (!(this.world || this.dimensionType)) {
return;
if (this.world || this.dimensionType) {
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
@SubscribeEvent
public void onPlayerChangeGameMode(PlayerEvent.PlayerChangeGameModeEvent event) {
if (!this.gamemode) {
return;
if (this.gamemode) {
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
}
@@ -1,97 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.forge.listeners;
import me.lucko.luckperms.common.api.implementation.ApiUser;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.forge.LPForgePlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.level.ServerPlayer;
import java.util.Map;
public class ForgeAutoOpListener implements LuckPermsEventListener {
private static final String NODE = "luckperms.autoop";
private final LPForgePlugin plugin;
public ForgeAutoOpListener(LPForgePlugin plugin) {
this.plugin = plugin;
}
@Override
public void bind(EventBus bus) {
bus.subscribe(ContextUpdateEvent.class, this::onContextUpdate);
bus.subscribe(UserDataRecalculateEvent.class, this::onUserDataRecalculate);
}
private void onContextUpdate(ContextUpdateEvent event) {
event.getSubject(ServerPlayer.class).ifPresent(player -> refreshAutoOp(player, true));
}
private void onUserDataRecalculate(UserDataRecalculateEvent event) {
User user = ApiUser.cast(event.getUser());
this.plugin.getBootstrap().getPlayer(user.getUniqueId()).ifPresent(player -> refreshAutoOp(player, false));
}
private void refreshAutoOp(ServerPlayer player, boolean callerIsSync) {
if (!callerIsSync && !this.plugin.getBootstrap().getServer().isPresent()) {
return;
}
User user = this.plugin.getUserManager().getIfLoaded(player.getUUID());
boolean value;
if (user != null) {
QueryOptions queryOptions = this.plugin.getContextManager().getQueryOptions(player);
Map<String, Boolean> permData = user.getCachedData().getPermissionData(queryOptions).getPermissionMap();
value = permData.getOrDefault(NODE, false);
} else {
value = false;
}
if (callerIsSync) {
setOp(player, value);
} else {
this.plugin.getBootstrap().getScheduler().executeSync(() -> setOp(player, value));
}
}
private void setOp(ServerPlayer player, boolean value) {
this.plugin.getBootstrap().getServer().ifPresent(server -> {
if (value) {
server.getPlayerList().op(player.nameAndId());
} else {
server.getPlayerList().deop(player.nameAndId());
}
});
}
}
@@ -30,8 +30,8 @@ import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.minecraft.command.BrigadierInjector;
import me.lucko.luckperms.forge.LPForgePlugin;
import me.lucko.luckperms.forge.util.BrigadierInjector;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.server.players.ServerOpList;
@@ -1,190 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.forge.util;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.graph.Graph;
import me.lucko.luckperms.common.graph.TraversalAlgorithm;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.forge.LPForgePlugin;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import java.util.function.Predicate;
/**
* Utility for injecting permission requirements into a Brigadier command tree.
*/
public final class BrigadierInjector {
private BrigadierInjector() {}
private static final Field REQUIREMENT_FIELD;
static {
Field requirementField;
try {
requirementField = CommandNode.class.getDeclaredField("requirement");
requirementField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new ExceptionInInitializerError(e);
}
REQUIREMENT_FIELD = requirementField;
}
/**
* Inject permission requirements into the commands in the given dispatcher.
*
* @param plugin the plugin
* @param dispatcher the command dispatcher
*/
public static void inject(LPForgePlugin plugin, CommandDispatcher<CommandSourceStack> dispatcher) {
Iterable<CommandNodeWithParent> tree = CommandNodeGraph.INSTANCE.traverse(
TraversalAlgorithm.DEPTH_FIRST_PRE_ORDER,
new CommandNodeWithParent(null, dispatcher.getRoot())
);
for (CommandNodeWithParent node : tree) {
Predicate<CommandSourceStack> requirement = node.node.getRequirement();
// already injected - skip
if (requirement instanceof InjectedPermissionRequirement) {
continue;
}
String permission = buildPermissionNode(node);
if (permission == null) {
continue;
}
plugin.getPermissionRegistry().insert(permission);
InjectedPermissionRequirement newRequirement = new InjectedPermissionRequirement(plugin, permission, requirement);
try {
REQUIREMENT_FIELD.set(node.node, newRequirement);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
private static String buildPermissionNode(CommandNodeWithParent node) {
StringBuilder builder = new StringBuilder();
while (node != null) {
if (node.node instanceof LiteralCommandNode) {
if (builder.length() != 0) {
builder.insert(0, '.');
}
String name = node.node.getName().toLowerCase(Locale.ROOT);
builder.insert(0, name);
}
node = node.parent;
}
if (builder.length() == 0) {
return null;
}
builder.insert(0, "command.");
return builder.toString();
}
/**
* Injected {@link CommandNode#getRequirement() requirement} that checks for a permission, before
* delegating to the existing requirement.
*/
private static final class InjectedPermissionRequirement implements Predicate<CommandSourceStack> {
private final LPForgePlugin plugin;
private final String permission;
private final Predicate<CommandSourceStack> delegate;
private InjectedPermissionRequirement(LPForgePlugin plugin, String permission, Predicate<CommandSourceStack> delegate) {
this.plugin = plugin;
this.permission = permission;
this.delegate = delegate;
}
@Override
public boolean test(CommandSourceStack source) {
if (source.getEntity() instanceof ServerPlayer player) {
User user = this.plugin.getUserManager().getIfLoaded(player.getUUID());
if (user == null) {
return false;
}
QueryOptions queryOptions = this.plugin.getContextManager().getQueryOptions(player);
Tristate state = user.getCachedData().getPermissionData(queryOptions).checkPermission(this.permission);
if (state != Tristate.UNDEFINED) {
return state.asBoolean() && this.delegate.test(source.withPermission(LevelBasedPermissionSet.OWNER));
}
}
return this.delegate.test(source);
}
}
/**
* A {@link Graph} to represent the brigadier command node tree.
*/
private enum CommandNodeGraph implements Graph<CommandNodeWithParent> {
INSTANCE;
@Override
public Iterable<? extends CommandNodeWithParent> successors(CommandNodeWithParent ctx) {
CommandNode<CommandSourceStack> node = ctx.node;
Collection<CommandNodeWithParent> successors = new ArrayList<>();
for (CommandNode<CommandSourceStack> child : node.getChildren()) {
successors.add(new CommandNodeWithParent(ctx, child));
}
return successors;
}
}
private static final class CommandNodeWithParent {
private final CommandNodeWithParent parent;
private final CommandNode<CommandSourceStack> node;
private CommandNodeWithParent(CommandNodeWithParent parent, CommandNode<CommandSourceStack> node) {
this.parent = parent;
this.node = node;
}
}
}
+1
View File
@@ -25,6 +25,7 @@ neoForge {
dependencies {
add('shade', project(':common'))
add('shade', project(':common:minecraft'))
compileOnly project(':common:loader-utils')
}
@@ -25,8 +25,9 @@
package me.lucko.luckperms.neoforge;
import com.mojang.authlib.GameProfile;
import me.lucko.luckperms.common.loader.LoaderBootstrap;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsBootstrap;
import me.lucko.luckperms.common.minecraft.MinecraftSchedulerAdapter;
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
@@ -37,9 +38,6 @@ import me.lucko.luckperms.common.plugin.scheduler.SchedulerAdapter;
import me.lucko.luckperms.neoforge.util.NeoForgeEventBusFacade;
import net.luckperms.api.platform.Platform;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.NameAndId;
import net.minecraft.server.players.PlayerList;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
@@ -53,19 +51,14 @@ import org.apache.maven.artifact.versioning.ArtifactVersion;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;
/**
* Bootstrap plugin for LuckPerms running on Forge.
*/
public final class LPNeoForgeBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
public final class LPNeoForgeBootstrap extends MinecraftLuckPermsBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
public static final String ID = "luckperms";
/**
@@ -115,7 +108,7 @@ public final class LPNeoForgeBootstrap implements LuckPermsBootstrap, LoaderBoot
public LPNeoForgeBootstrap(Supplier<ModContainer> loader) {
this.loader = loader;
this.logger = new Log4jPluginLogger(LogManager.getLogger(LPNeoForgeBootstrap.ID));
this.schedulerAdapter = new NeoForgeSchedulerAdapter(this);
this.schedulerAdapter = new MinecraftSchedulerAdapter(this);
this.classPathAppender = new JarInJarClassPathAppender(getClass().getClassLoader());
this.forgeEventBus = new NeoForgeEventBusFacade();
this.plugin = new LPNeoForgePlugin(this);
@@ -189,8 +182,7 @@ public final class LPNeoForgeBootstrap implements LuckPermsBootstrap, LoaderBoot
return this.enableLatch;
}
// MinecraftServer singleton getter
@Override
public Optional<MinecraftServer> getServer() {
return Optional.ofNullable(this.server);
}
@@ -238,51 +230,4 @@ public final class LPNeoForgeBootstrap implements LuckPermsBootstrap, LoaderBoot
return FMLPaths.CONFIGDIR.get().resolve(LPNeoForgeBootstrap.ID).toAbsolutePath();
}
@Override
public Optional<ServerPlayer> getPlayer(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList).map(playerList -> playerList.getPlayer(uniqueId));
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
return getServer().map(s -> s.services().nameToIdCache()).flatMap(profileCache -> profileCache.get(username)).map(NameAndId::id);
}
@Override
public Optional<String> lookupUsername(UUID uniqueId) {
return getServer().map(s -> s.services().nameToIdCache()).flatMap(profileCache -> profileCache.get(uniqueId)).map(NameAndId::name);
}
@Override
public int getPlayerCount() {
return getServer().map(MinecraftServer::getPlayerCount).orElse(0);
}
@Override
public Collection<String> getPlayerList() {
return getServer().map(MinecraftServer::getPlayerList).map(PlayerList::getPlayers).map(players -> {
List<String> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().name());
}
return list;
}).orElse(Collections.emptyList());
}
@Override
public Collection<UUID> getOnlinePlayers() {
return getServer().map(MinecraftServer::getPlayerList).map(PlayerList::getPlayers).map(players -> {
List<UUID> list = new ArrayList<>(players.size());
for (ServerPlayer player : players) {
list.add(player.getGameProfile().id());
}
return list;
}).orElse(Collections.emptyList());
}
@Override
public boolean isPlayerOnline(UUID uniqueId) {
return getServer().map(MinecraftServer::getPlayerList).map(playerList -> playerList.getPlayer(uniqueId)).isPresent();
}
}
@@ -26,63 +26,37 @@
package me.lucko.luckperms.neoforge;
import me.lucko.luckperms.common.api.LuckPermsApiProvider;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.generic.adapter.ConfigurationAdapter;
import me.lucko.luckperms.common.dependencies.Dependency;
import me.lucko.luckperms.common.event.AbstractEventBus;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.messaging.MessagingFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.model.manager.group.StandardGroupManager;
import me.lucko.luckperms.common.model.manager.track.StandardTrackManager;
import me.lucko.luckperms.common.model.manager.user.StandardUserManager;
import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
import me.lucko.luckperms.common.sender.DummyConsoleSender;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.neoforge.calculator.NeoForgeCalculatorFactory;
import me.lucko.luckperms.common.minecraft.MinecraftLuckPermsPlugin;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftAutoOpListener;
import me.lucko.luckperms.common.minecraft.listeners.MinecraftCommandListUpdater;
import me.lucko.luckperms.neoforge.context.NeoForgeContextManager;
import me.lucko.luckperms.neoforge.context.NeoForgePlayerCalculator;
import me.lucko.luckperms.neoforge.listeners.NeoForgeAutoOpListener;
import me.lucko.luckperms.neoforge.listeners.NeoForgeCommandListUpdater;
import me.lucko.luckperms.neoforge.listeners.NeoForgeConnectionListener;
import me.lucko.luckperms.neoforge.listeners.NeoForgePlatformListener;
import me.lucko.luckperms.neoforge.messaging.NeoForgeMessagingFactory;
import me.lucko.luckperms.neoforge.messaging.PluginMessageMessenger;
import me.lucko.luckperms.neoforge.service.NeoForgePermissionHandlerListener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.players.PlayerList;
import net.neoforged.fml.ModContainer;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
/**
* LuckPerms implementation for Forge.
*/
public class LPNeoForgePlugin extends AbstractLuckPermsPlugin {
private final LPNeoForgeBootstrap bootstrap;
public class LPNeoForgePlugin extends MinecraftLuckPermsPlugin<LPNeoForgePlugin, LPNeoForgeBootstrap> {
private NeoForgeSenderFactory senderFactory;
private NeoForgeConnectionListener connectionListener;
private NeoForgeCommandExecutor commandManager;
private StandardUserManager userManager;
private StandardGroupManager groupManager;
private StandardTrackManager trackManager;
private NeoForgeContextManager contextManager;
public LPNeoForgePlugin(LPNeoForgeBootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public LPNeoForgeBootstrap getBootstrap() {
return this.bootstrap;
super(bootstrap);
}
protected void registerEarlyListeners() {
@@ -137,18 +111,6 @@ public class LPNeoForgePlugin extends AbstractLuckPermsPlugin {
// Too late for Forge, registered in #registerEarlyListeners
}
@Override
protected void setupManagers() {
this.userManager = new StandardUserManager(this);
this.groupManager = new StandardGroupManager(this);
this.trackManager = new StandardTrackManager(this);
}
@Override
protected CalculatorFactory provideCalculatorFactory() {
return new NeoForgeCalculatorFactory(this);
}
@Override
protected void setupContextManager() {
this.contextManager = new NeoForgeContextManager(this);
@@ -175,43 +137,15 @@ public class LPNeoForgePlugin extends AbstractLuckPermsPlugin {
protected void performFinalSetup() {
// register autoop listener
if (getConfiguration().get(ConfigKeys.AUTO_OP)) {
getApiProvider().getEventBus().subscribe(new NeoForgeAutoOpListener(this));
getApiProvider().getEventBus().subscribe(new MinecraftAutoOpListener(this));
}
// register forge command list updater
if (getConfiguration().get(ConfigKeys.UPDATE_CLIENT_COMMAND_LIST)) {
getApiProvider().getEventBus().subscribe(new NeoForgeCommandListUpdater(this));
getApiProvider().getEventBus().subscribe(new MinecraftCommandListUpdater(this));
}
}
@Override
public Optional<QueryOptions> getQueryOptionsForUser(User user) {
return this.bootstrap.getPlayer(user.getUniqueId()).map(player -> this.contextManager.getQueryOptions(player));
}
@Override
public Stream<Sender> getOnlineSenders() {
return Stream.concat(
Stream.of(getConsoleSender()),
this.bootstrap.getServer()
.map(MinecraftServer::getPlayerList)
.map(PlayerList::getPlayers)
.map(players -> players.stream().map(player -> this.senderFactory.wrap(player.createCommandSourceStack()))).orElseGet(Stream::empty)
);
}
@Override
public Sender getConsoleSender() {
return this.bootstrap.getServer()
.map(server -> this.senderFactory.wrap(server.createCommandSourceStack()))
.orElseGet(() -> new DummyConsoleSender(this) {
@Override
public void sendMessage(Component message) {
LPNeoForgePlugin.this.bootstrap.getPluginLogger().info(PlainTextComponentSerializer.plainText().serialize(TranslationManager.render(message)));
}
});
}
public NeoForgeSenderFactory getSenderFactory() {
return this.senderFactory;
}
@@ -226,21 +160,6 @@ public class LPNeoForgePlugin extends AbstractLuckPermsPlugin {
return this.commandManager;
}
@Override
public StandardUserManager getUserManager() {
return this.userManager;
}
@Override
public StandardGroupManager getGroupManager() {
return this.groupManager;
}
@Override
public StandardTrackManager getTrackManager() {
return this.trackManager;
}
@Override
public NeoForgeContextManager getContextManager() {
return this.contextManager;
@@ -25,94 +25,17 @@
package me.lucko.luckperms.neoforge;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.command.BrigadierCommandExecutor;
import me.lucko.luckperms.common.sender.Sender;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import net.minecraft.server.permissions.Permission;
import net.minecraft.server.permissions.PermissionLevel;
import me.lucko.luckperms.common.minecraft.command.MinecraftCommandExecutor;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import java.util.List;
import java.util.ListIterator;
public class NeoForgeCommandExecutor extends BrigadierCommandExecutor<CommandSourceStack> {
private final LPNeoForgePlugin plugin;
public class NeoForgeCommandExecutor extends MinecraftCommandExecutor {
public NeoForgeCommandExecutor(LPNeoForgePlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@SubscribeEvent
public void onRegisterCommands(RegisterCommandsEvent event) {
for (String alias : COMMAND_ALIASES) {
LiteralCommandNode<CommandSourceStack> command = Commands.literal(alias).executes(this).build();
ArgumentCommandNode<CommandSourceStack, String> argument = Commands.argument("args", StringArgumentType.greedyString())
.suggests(this)
.executes(this)
.build();
command.addChild(argument);
event.getDispatcher().getRoot().addChild(command);
}
register(event.getDispatcher());
}
@Override
public Sender getSender(CommandSourceStack source) {
return this.plugin.getSenderFactory().wrap(source);
}
@Override
public List<String> resolveSelectors(CommandSourceStack source, List<String> args) {
// usage of @ selectors requires at least level 2 permission
CommandSourceStack atAllowedSource = ensureSourceCanUseSelectors(source);
for (ListIterator<String> it = args.listIterator(); it.hasNext(); ) {
String arg = it.next();
if (arg.isEmpty() || arg.charAt(0) != '@') {
continue;
}
List<ServerPlayer> matchedPlayers;
try {
matchedPlayers = EntityArgument.entities().parse(new StringReader(arg)).findPlayers(atAllowedSource);
} catch (CommandSyntaxException e) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args, e);
continue;
}
if (matchedPlayers.isEmpty()) {
continue;
}
if (matchedPlayers.size() > 1) {
this.plugin.getLogger().warn("Error parsing selector '" + arg + "' for " + source + " executing " + args +
": ambiguous result (more than one player matched) - " + matchedPlayers);
continue;
}
ServerPlayer player = matchedPlayers.get(0);
it.set(player.getStringUUID());
}
return args;
}
private static CommandSourceStack ensureSourceCanUseSelectors(CommandSourceStack source) {
if (source.permissions().hasPermission(new Permission.HasCommandLevel(PermissionLevel.GAMEMASTERS))) {
return source;
}
return source.withMaximumPermission(LevelBasedPermissionSet.GAMEMASTER);
}
}
@@ -25,58 +25,26 @@
package me.lucko.luckperms.neoforge;
import com.mojang.brigadier.ParseResults;
import com.mojang.serialization.JsonOps;
import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.locale.TranslationManager;
import me.lucko.luckperms.common.minecraft.MinecraftSenderFactory;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.query.QueryOptionsImpl;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.sender.SenderFactory;
import me.lucko.luckperms.common.verbose.VerboseCheckTarget;
import me.lucko.luckperms.common.verbose.event.CheckOrigin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.luckperms.api.query.QueryOptions;
import net.luckperms.api.util.Tristate;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.rcon.RconConsoleSource;
import net.minecraft.world.entity.player.Player;
import java.util.Locale;
import java.util.UUID;
public class NeoForgeSenderFactory extends SenderFactory<LPNeoForgePlugin, CommandSourceStack> {
public class NeoForgeSenderFactory extends MinecraftSenderFactory<LPNeoForgePlugin> {
public NeoForgeSenderFactory(LPNeoForgePlugin plugin) {
super(plugin);
}
@Override
protected UUID getUniqueId(CommandSourceStack commandSource) {
if (commandSource.getEntity() instanceof Player) {
return commandSource.getEntity().getUUID();
}
return Sender.CONSOLE_UUID;
}
@Override
protected String getName(CommandSourceStack commandSource) {
if (commandSource.getEntity() instanceof Player) {
return commandSource.getTextName();
}
return Sender.CONSOLE_NAME;
}
@Override
protected void sendMessage(CommandSourceStack sender, Component message) {
Locale locale = sender.getEntity() instanceof ServerPlayer player
? TranslationManager.parseLocale(player.getLanguage())
: null;
sender.sendSuccess(() -> toNativeText(TranslationManager.render(message, locale)), false);
protected CommandSource getSource(CommandSourceStack sender) {
return sender.source;
}
@Override
@@ -96,31 +64,4 @@ public class NeoForgeSenderFactory extends SenderFactory<LPNeoForgePlugin, Comma
getPlugin().getPermissionRegistry().offer(node);
return Tristate.UNDEFINED;
}
@Override
protected boolean hasPermission(CommandSourceStack commandSource, String node) {
return getPermissionValue(commandSource, node).asBoolean();
}
@Override
protected void performCommand(CommandSourceStack sender, String command) {
ParseResults<CommandSourceStack> results = sender.getServer().getCommands().getDispatcher().parse(command, sender);
sender.getServer().getCommands().performCommand(results, command);
}
@Override
protected boolean isConsole(CommandSourceStack sender) {
CommandSource output = sender.source;
return output == sender.getServer() || // Console
output.getClass() == RconConsoleSource.class || // Rcon
(output == CommandSource.NULL && sender.getTextName().equals("")); // Functions
}
public static net.minecraft.network.chat.Component toNativeText(Component component) {
return ComponentSerialization.CODEC.decode(
RegistryAccess.EMPTY.createSerializationContext(JsonOps.INSTANCE),
GsonComponentSerializer.gson().serializeToTree(component)
).getOrThrow(IllegalArgumentException::new).getFirst();
}
}
@@ -1,77 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.neoforge.calculator;
import me.lucko.luckperms.common.cacheddata.CacheMetadata;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.calculator.PermissionCalculator;
import me.lucko.luckperms.common.calculator.processor.DirectProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import me.lucko.luckperms.common.calculator.processor.RegexProcessor;
import me.lucko.luckperms.common.calculator.processor.SpongeWildcardProcessor;
import me.lucko.luckperms.common.calculator.processor.WildcardProcessor;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import me.lucko.luckperms.neoforge.context.NeoForgeContextManager;
import net.luckperms.api.query.QueryOptions;
import java.util.ArrayList;
import java.util.List;
public class NeoForgeCalculatorFactory implements CalculatorFactory {
private final LPNeoForgePlugin plugin;
public NeoForgeCalculatorFactory(LPNeoForgePlugin plugin) {
this.plugin = plugin;
}
@Override
public PermissionCalculator build(QueryOptions queryOptions, CacheMetadata metadata) {
List<PermissionProcessor> processors = new ArrayList<>(5);
processors.add(new DirectProcessor());
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX)) {
processors.add(new RegexProcessor());
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_WILDCARDS)) {
processors.add(new WildcardProcessor());
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_WILDCARDS_SPONGE)) {
processors.add(new SpongeWildcardProcessor());
}
boolean integratedOwner = queryOptions.option(NeoForgeContextManager.INTEGRATED_SERVER_OWNER).orElse(false);
if (integratedOwner && this.plugin.getConfiguration().get(ConfigKeys.INTEGRATED_SERVER_OWNER_BYPASSES_CHECKS)) {
processors.add(ServerOwnerProcessor.INSTANCE);
}
return new PermissionCalculator(this.plugin, metadata, processors);
}
}
@@ -26,17 +26,14 @@
package me.lucko.luckperms.neoforge.context;
import me.lucko.luckperms.common.context.manager.SimpleContextManager;
import me.lucko.luckperms.common.minecraft.context.MinecraftContextManager;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import net.luckperms.api.query.OptionKey;
import net.luckperms.api.query.QueryOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.util.UUID;
public class NeoForgeContextManager extends SimpleContextManager<ServerPlayer, ServerPlayer> {
public static final OptionKey<Boolean> INTEGRATED_SERVER_OWNER = OptionKey.of("integrated_server_owner", Boolean.class);
public class NeoForgeContextManager extends SimpleContextManager<ServerPlayer, ServerPlayer> implements MinecraftContextManager {
public NeoForgeContextManager(LPNeoForgePlugin plugin) {
super(plugin, ServerPlayer.class, ServerPlayer.class);
}
@@ -48,8 +45,7 @@ public class NeoForgeContextManager extends SimpleContextManager<ServerPlayer, S
@Override
public void customizeQueryOptions(ServerPlayer subject, QueryOptions.Builder builder) {
MinecraftServer server = subject.level().getServer();
if (server != null && server.isSingleplayerOwner(subject.nameAndId())) {
if (subject.level().getServer().isSingleplayerOwner(subject.nameAndId())) {
builder.option(INTEGRATED_SERVER_OWNER, true);
}
}
@@ -25,114 +25,31 @@
package me.lucko.luckperms.neoforge.context;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import me.lucko.luckperms.common.minecraft.context.MinecraftPlayerCalculator;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import net.luckperms.api.context.Context;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextConsumer;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.ImmutableContextSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.storage.ServerLevelData;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Set;
public class NeoForgePlayerCalculator implements ContextCalculator<ServerPlayer> {
private final LPNeoForgePlugin plugin;
private final boolean gamemode;
private final boolean world;
private final boolean dimensionType;
public class NeoForgePlayerCalculator extends MinecraftPlayerCalculator {
public NeoForgePlayerCalculator(LPNeoForgePlugin plugin, Set<String> disabled) {
this.plugin = plugin;
this.gamemode = !disabled.contains(DefaultContextKeys.GAMEMODE_KEY);
this.world = !disabled.contains(DefaultContextKeys.WORLD_KEY);
this.dimensionType = !disabled.contains(DefaultContextKeys.DIMENSION_TYPE_KEY);
}
@Override
public void calculate(@NonNull ServerPlayer target, @NonNull ContextConsumer consumer) {
ServerLevel level = target.level();
if (this.dimensionType) {
consumer.accept(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(level.dimension().identifier()));
}
if (this.world) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
this.plugin.getConfiguration().get(ConfigKeys.WORLD_REWRITES).rewriteAndSubmit(levelData.getLevelName(), consumer);
}
if (this.gamemode) {
GameType gameMode = target.gameMode.getGameModeForPlayer();
consumer.accept(DefaultContextKeys.GAMEMODE_KEY, gameMode.getName());
}
}
@Override
public @NonNull ContextSet estimatePotentialContexts() {
ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
if (this.gamemode) {
for (GameType gameType : GameType.values()) {
builder.add(DefaultContextKeys.GAMEMODE_KEY, gameType.getName());
}
}
MinecraftServer server = this.plugin.getBootstrap().getServer().orElse(null);
if (this.dimensionType && server != null) {
server.registryAccess().lookup(Registries.DIMENSION_TYPE).ifPresent(registry -> {
for (Identifier id : registry.keySet()) {
builder.add(DefaultContextKeys.DIMENSION_TYPE_KEY, getContextKey(id));
}
});
}
if (this.world && server != null) {
for (ServerLevel level : server.getAllLevels()) {
ServerLevelData levelData = (ServerLevelData) level.getLevelData();
if (Context.isValidValue(levelData.getLevelName())) {
builder.add(DefaultContextKeys.WORLD_KEY, levelData.getLevelName());
}
}
}
return builder.build();
}
private static String getContextKey(Identifier key) {
if (key.getNamespace().equals("minecraft")) {
return key.getPath();
}
return key.toString();
super(plugin, disabled);
}
@SubscribeEvent
public void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
if (!(this.world || this.dimensionType)) {
return;
if (this.world || this.dimensionType) {
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
@SubscribeEvent
public void onPlayerChangeGameMode(PlayerEvent.PlayerChangeGameModeEvent event) {
if (!this.gamemode) {
return;
if (this.gamemode) {
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
this.plugin.getContextManager().signalContextUpdate((ServerPlayer) event.getEntity());
}
}
@@ -1,119 +0,0 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.neoforge.listeners;
import com.github.benmanes.caffeine.cache.LoadingCache;
import me.lucko.luckperms.common.api.implementation.ApiGroup;
import me.lucko.luckperms.common.cache.BufferedRequest;
import me.lucko.luckperms.common.event.LuckPermsEventListener;
import me.lucko.luckperms.common.util.CaffeineFactory;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import net.luckperms.api.event.EventBus;
import net.luckperms.api.event.context.ContextUpdateEvent;
import net.luckperms.api.event.group.GroupDataRecalculateEvent;
import net.luckperms.api.event.user.UserDataRecalculateEvent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Calls {@link net.minecraft.server.players.PlayerList#sendPlayerPermissionLevel(ServerPlayer)} when a players permissions change.
*/
public class NeoForgeCommandListUpdater implements LuckPermsEventListener {
private final LPNeoForgePlugin plugin;
private final LoadingCache<UUID, SendBuffer> sendingBuffers = CaffeineFactory.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.build(SendBuffer::new);
public NeoForgeCommandListUpdater(LPNeoForgePlugin plugin) {
this.plugin = plugin;
}
@Override
public void bind(EventBus bus) {
bus.subscribe(UserDataRecalculateEvent.class, this::onUserDataRecalculate);
bus.subscribe(GroupDataRecalculateEvent.class, this::onGroupDataRecalculate);
bus.subscribe(ContextUpdateEvent.class, this::onContextUpdate);
}
private void onUserDataRecalculate(UserDataRecalculateEvent e) {
requestUpdate(e.getUser().getUniqueId());
}
private void onGroupDataRecalculate(GroupDataRecalculateEvent e) {
plugin.getUserManager().getAll().values().forEach(user -> {
if (user.resolveInheritanceTree(user.getQueryOptions()).contains(ApiGroup.cast(e.getGroup()))) {
requestUpdate(user.getUniqueId());
}
});
}
private void onContextUpdate(ContextUpdateEvent e) {
e.getSubject(ServerPlayer.class).ifPresent(p -> requestUpdate(p.getUUID()));
}
private void requestUpdate(UUID uniqueId) {
if (!this.plugin.getBootstrap().isPlayerOnline(uniqueId)) {
return;
}
// Buffer the request to send a commands update.
SendBuffer sendBuffer = this.sendingBuffers.get(uniqueId);
if (sendBuffer != null) {
sendBuffer.request();
}
}
// Called when the buffer times out.
private void sendUpdate(UUID uniqueId) {
this.plugin.getBootstrap().getScheduler().sync().execute(() -> {
this.plugin.getBootstrap().getPlayer(uniqueId).ifPresent(player -> {
MinecraftServer server = player.level().getServer();
if (server != null) {
server.getPlayerList().sendPlayerPermissionLevel(player);
}
});
});
}
private final class SendBuffer extends BufferedRequest<Void> {
private final UUID uniqueId;
SendBuffer(UUID uniqueId) {
super(500, TimeUnit.MILLISECONDS, NeoForgeCommandListUpdater.this.plugin.getBootstrap().getScheduler());
this.uniqueId = uniqueId;
}
@Override
protected Void perform() {
sendUpdate(this.uniqueId);
return null;
}
}
}
@@ -30,8 +30,8 @@ import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.minecraft.command.BrigadierInjector;
import me.lucko.luckperms.neoforge.LPNeoForgePlugin;
import me.lucko.luckperms.neoforge.util.BrigadierInjector;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.server.players.ServerOpList;
+1
View File
@@ -21,6 +21,7 @@ include (
'api',
'common',
'common:loader-utils',
'common:minecraft',
'bukkit',
'bukkit:loader',
'bukkit-legacy',