Cleanup / tidy up a number of classes

This commit is contained in:
Luck 2017-10-29 12:58:45 +00:00
parent ebe12f838c
commit 72e6c75433
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
82 changed files with 800 additions and 581 deletions

View File

@ -29,6 +29,7 @@ import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import me.lucko.luckperms.common.commands.CommandManager; import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.commands.utils.Util;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -36,29 +37,33 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import java.util.Arrays;
import java.util.List; import java.util.List;
public class BukkitCommand extends CommandManager implements CommandExecutor, TabExecutor { public class BukkitCommandExecutor extends CommandManager implements CommandExecutor, TabExecutor {
private static final Splitter ARGUMENT_SPLITTER = Splitter.on(COMMAND_SEPARATOR_PATTERN).omitEmptyStrings();
private static final Joiner ARGUMENT_JOINER = Joiner.on(' ');
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
BukkitCommand(LPBukkitPlugin plugin) { BukkitCommandExecutor(LPBukkitPlugin plugin) {
super(plugin); super(plugin);
this.plugin = plugin; this.plugin = plugin;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
onCommand( Sender lpSender = plugin.getSenderFactory().wrap(sender);
plugin.getSenderFactory().wrap(sender), List<String> arguments = Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(ARGUMENT_JOINER.join(args)));
label,
Util.stripQuotes(Splitter.on(COMMAND_SEPARATOR_PATTERN).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))) onCommand(lpSender, label, arguments);
);
return true; return true;
} }
@Override @Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
return onTabComplete(plugin.getSenderFactory().wrap(sender), Arrays.asList(args)); Sender lpSender = plugin.getSenderFactory().wrap(sender);
List<String> arguments = Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(ARGUMENT_JOINER.join(args)));
return onTabComplete(lpSender, arguments);
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.bukkit;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.common.config.AbstractConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -41,7 +41,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
@RequiredArgsConstructor @RequiredArgsConstructor
public class BukkitConfig extends AbstractConfiguration { public class BukkitConfigAdapter implements ConfigurationAdapter {
@Getter @Getter
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;

View File

@ -29,7 +29,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import me.lucko.luckperms.common.plugin.LuckPermsScheduler; import me.lucko.luckperms.common.plugin.SchedulerAdapter;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
@ -40,7 +40,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class LPBukkitScheduler implements LuckPermsScheduler { public class BukkitSchedulerAdapter implements SchedulerAdapter {
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
@Getter @Getter
@ -55,23 +55,23 @@ public class LPBukkitScheduler implements LuckPermsScheduler {
@Accessors(fluent = true) @Accessors(fluent = true)
private Executor sync; private Executor sync;
@Getter
@Accessors(fluent = true)
private Executor async;
@Getter @Getter
@Setter @Setter
private boolean useBukkitAsync = false; private boolean useBukkitAsync = false;
private final Set<BukkitTask> tasks = ConcurrentHashMap.newKeySet(); private final Set<BukkitTask> tasks = ConcurrentHashMap.newKeySet();
public LPBukkitScheduler(LPBukkitPlugin plugin) { public BukkitSchedulerAdapter(LPBukkitPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
this.asyncLp = Executors.newCachedThreadPool(); this.asyncLp = Executors.newCachedThreadPool();
this.asyncBukkit = r -> plugin.getServer().getScheduler().runTaskAsynchronously(plugin, r); this.asyncBukkit = r -> plugin.getServer().getScheduler().runTaskAsynchronously(plugin, r);
this.sync = r -> plugin.getServer().getScheduler().runTask(plugin, r); this.sync = r -> plugin.getServer().getScheduler().runTask(plugin, r);
} this.async = r -> (useBukkitAsync ? asyncBukkit : asyncLp).execute(r);
@Override
public Executor async() {
return useBukkitAsync ? asyncBukkit : asyncLp;
} }
@Override @Override

View File

@ -25,6 +25,8 @@
package me.lucko.luckperms.bukkit; package me.lucko.luckperms.bukkit;
import lombok.AllArgsConstructor;
import me.lucko.luckperms.api.Tristate; import me.lucko.luckperms.api.Tristate;
import me.lucko.luckperms.bukkit.compat.MessageHandler; import me.lucko.luckperms.bukkit.compat.MessageHandler;
import me.lucko.luckperms.common.commands.sender.SenderFactory; import me.lucko.luckperms.common.commands.sender.SenderFactory;
@ -68,7 +70,7 @@ public class BukkitSenderFactory extends SenderFactory<CommandSender> {
// send sync if command block // send sync if command block
if (sender instanceof BlockCommandSender) { if (sender instanceof BlockCommandSender) {
getPlugin().getScheduler().doSync(() -> sender.sendMessage(s)); getPlugin().getScheduler().doSync(new BlockMessageAgent(((BlockCommandSender) sender), s));
return; return;
} }
@ -92,4 +94,16 @@ public class BukkitSenderFactory extends SenderFactory<CommandSender> {
protected boolean hasPermission(CommandSender sender, String node) { protected boolean hasPermission(CommandSender sender, String node) {
return sender.hasPermission(node); return sender.hasPermission(node);
} }
@AllArgsConstructor
private static final class BlockMessageAgent implements Runnable {
private final BlockCommandSender block;
private final String message;
@Override
public void run() {
block.sendMessage(message);
}
}
} }

View File

@ -34,9 +34,12 @@ import me.lucko.luckperms.api.PlatformType;
import me.lucko.luckperms.bukkit.calculators.BukkitCalculatorFactory; import me.lucko.luckperms.bukkit.calculators.BukkitCalculatorFactory;
import me.lucko.luckperms.bukkit.contexts.BukkitContextManager; import me.lucko.luckperms.bukkit.contexts.BukkitContextManager;
import me.lucko.luckperms.bukkit.contexts.WorldCalculator; import me.lucko.luckperms.bukkit.contexts.WorldCalculator;
import me.lucko.luckperms.bukkit.listeners.BukkitConnectionListener;
import me.lucko.luckperms.bukkit.listeners.BukkitPlatformListener;
import me.lucko.luckperms.bukkit.messaging.BukkitMessagingFactory; import me.lucko.luckperms.bukkit.messaging.BukkitMessagingFactory;
import me.lucko.luckperms.bukkit.model.Injector; import me.lucko.luckperms.bukkit.model.Injector;
import me.lucko.luckperms.bukkit.model.LPPermissible; import me.lucko.luckperms.bukkit.model.LPPermissible;
import me.lucko.luckperms.bukkit.processors.BukkitProcessorsSetupTask;
import me.lucko.luckperms.bukkit.processors.ChildPermissionProvider; import me.lucko.luckperms.bukkit.processors.ChildPermissionProvider;
import me.lucko.luckperms.bukkit.processors.DefaultsProvider; import me.lucko.luckperms.bukkit.processors.DefaultsProvider;
import me.lucko.luckperms.bukkit.vault.VaultHookManager; import me.lucko.luckperms.bukkit.vault.VaultHookManager;
@ -48,6 +51,7 @@ import me.lucko.luckperms.common.buffers.UpdateTaskBuffer;
import me.lucko.luckperms.common.caching.handlers.CachedStateManager; import me.lucko.luckperms.common.caching.handlers.CachedStateManager;
import me.lucko.luckperms.common.calculators.CalculatorFactory; import me.lucko.luckperms.common.calculators.CalculatorFactory;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.config.AbstractConfiguration;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.LuckPermsConfiguration;
import me.lucko.luckperms.common.constants.CommandPermission; import me.lucko.luckperms.common.constants.CommandPermission;
@ -65,7 +69,7 @@ import me.lucko.luckperms.common.managers.GenericUserManager;
import me.lucko.luckperms.common.managers.GroupManager; import me.lucko.luckperms.common.managers.GroupManager;
import me.lucko.luckperms.common.managers.TrackManager; import me.lucko.luckperms.common.managers.TrackManager;
import me.lucko.luckperms.common.managers.UserManager; import me.lucko.luckperms.common.managers.UserManager;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
@ -92,16 +96,14 @@ import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors; import java.util.stream.Stream;
/** /**
* LuckPerms implementation for the Bukkit API. * LuckPerms implementation for the Bukkit API.
@ -110,8 +112,8 @@ import java.util.stream.Collectors;
public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin { public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
private long startTime; private long startTime;
private LPBukkitScheduler scheduler; private BukkitSchedulerAdapter scheduler;
private BukkitCommand commandManager; private BukkitCommandExecutor commandManager;
private VaultHookManager vaultHookManager = null; private VaultHookManager vaultHookManager = null;
private LuckPermsConfiguration configuration; private LuckPermsConfiguration configuration;
private UserManager userManager; private UserManager userManager;
@ -119,9 +121,8 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
private TrackManager trackManager; private TrackManager trackManager;
private Storage storage; private Storage storage;
private FileWatcher fileWatcher = null; private FileWatcher fileWatcher = null;
private InternalMessagingService messagingService = null; private ExtendedMessagingService messagingService = null;
private UuidCache uuidCache; private UuidCache uuidCache;
private BukkitListener listener;
private ApiProvider apiProvider; private ApiProvider apiProvider;
private Logger log; private Logger log;
private DefaultsProvider defaultsProvider; private DefaultsProvider defaultsProvider;
@ -146,7 +147,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
} }
// setup minimal functionality in order to load initial dependencies // setup minimal functionality in order to load initial dependencies
scheduler = new LPBukkitScheduler(this); scheduler = new BukkitSchedulerAdapter(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new BukkitSenderFactory(this); senderFactory = new BukkitSenderFactory(this);
log = new SenderLogger(this, getConsoleSender()); log = new SenderLogger(this, getConsoleSender());
@ -186,9 +187,8 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
logDispatcher = new LogDispatcher(this); logDispatcher = new LogDispatcher(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new BukkitConfig(this); configuration = new AbstractConfiguration(this, new BukkitConfigAdapter(this));
configuration.init(); configuration.init();
configuration.loadAll();
Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2); Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2);
DependencyManager.loadStorageDependencies(this, storageTypes); DependencyManager.loadStorageDependencies(this, storageTypes);
@ -198,22 +198,11 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
childPermissionProvider = new ChildPermissionProvider(); childPermissionProvider = new ChildPermissionProvider();
// give all plugins a chance to load their permissions, then refresh. // give all plugins a chance to load their permissions, then refresh.
scheduler.syncLater(() -> { scheduler.syncLater(new BukkitProcessorsSetupTask(this), 1L);
defaultsProvider.refresh();
childPermissionProvider.setup();
Set<String> perms = new HashSet<>();
getServer().getPluginManager().getPermissions().forEach(p -> {
perms.add(p.getName());
perms.addAll(p.getChildren().keySet());
});
perms.forEach(p -> permissionVault.offer(p));
}, 1L);
// register events // register events
listener = new BukkitListener(this); getServer().getPluginManager().registerEvents(new BukkitConnectionListener(this), this);
getServer().getPluginManager().registerEvents(listener, this); getServer().getPluginManager().registerEvents(new BukkitPlatformListener(this), this);
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
@ -234,7 +223,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
localeManager.tryLoad(this, new File(getDataFolder(), "lang.yml")); localeManager.tryLoad(this, new File(getDataFolder(), "lang.yml"));
// register commands // register commands
commandManager = new BukkitCommand(this); commandManager = new BukkitCommandExecutor(this);
PluginCommand main = getServer().getPluginCommand("luckperms"); PluginCommand main = getServer().getPluginCommand("luckperms");
main.setExecutor(commandManager); main.setExecutor(commandManager);
main.setTabCompleter(commandManager); main.setTabCompleter(commandManager);
@ -282,7 +271,12 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
// register permissions // register permissions
try { try {
registerPermissions(getConfiguration().get(ConfigKeys.COMMANDS_ALLOW_OP) ? PermissionDefault.OP : PermissionDefault.FALSE); PluginManager pm = getServer().getPluginManager();
PermissionDefault permDefault = getConfiguration().get(ConfigKeys.COMMANDS_ALLOW_OP) ? PermissionDefault.OP : PermissionDefault.FALSE;
for (CommandPermission p : CommandPermission.values()) {
pm.addPermission(new org.bukkit.permissions.Permission(p.getPermission(), permDefault));
}
} catch (Exception e) { } catch (Exception e) {
// this throws an exception if the plugin is /reloaded, grr // this throws an exception if the plugin is /reloaded, grr
} }
@ -414,6 +408,15 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
} }
} }
@Override
public Optional<ExtendedMessagingService> getMessagingService() {
return Optional.ofNullable(messagingService);
}
public Optional<FileWatcher> getFileWatcher() {
return Optional.ofNullable(fileWatcher);
}
@Override @Override
public String getVersion() { public String getVersion() {
return getDescription().getVersion(); return getDescription().getVersion();
@ -475,13 +478,13 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<String> getPlayerList() { public Stream<String> getPlayerList() {
return getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); return getServer().getOnlinePlayers().stream().map(Player::getName);
} }
@Override @Override
public Set<UUID> getOnlinePlayers() { public Stream<UUID> getOnlinePlayers() {
return getServer().getOnlinePlayers().stream().map(Player::getUniqueId).collect(Collectors.toSet()); return getServer().getOnlinePlayers().stream().map(Player::getUniqueId);
} }
@Override @Override
@ -491,10 +494,11 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getOnlineSenders() { public Stream<Sender> getOnlineSenders() {
return getServer().getOnlinePlayers().stream() return Stream.concat(
.map(p -> getSenderFactory().wrap(p)) Stream.of(getConsoleSender()),
.collect(Collectors.toList()); getServer().getOnlinePlayers().stream().map(p -> getSenderFactory().wrap(p))
);
} }
@Override @Override
@ -511,14 +515,6 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
return map; return map;
} }
private void registerPermissions(PermissionDefault def) {
PluginManager pm = getServer().getPluginManager();
for (CommandPermission p : CommandPermission.values()) {
pm.addPermission(new org.bukkit.permissions.Permission(p.getPermission(), def));
}
}
private static boolean checkInvalidVersion() { private static boolean checkInvalidVersion() {
try { try {
Class.forName("com.google.gson.JsonElement"); Class.forName("com.google.gson.JsonElement");

View File

@ -71,11 +71,8 @@ public class BukkitCalculatorFactory extends AbstractCalculatorFactory {
processors.add(new DefaultsProcessor(contexts.isOp(), plugin.getDefaultsProvider())); processors.add(new DefaultsProcessor(contexts.isOp(), plugin.getDefaultsProvider()));
} }
return registerCalculator(new PermissionCalculator( PermissionCalculatorMetadata meta = PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts());
plugin, return registerCalculator(new PermissionCalculator(plugin, meta, processors.build()));
PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts()),
processors.build()
));
} }
@Override @Override

View File

@ -23,10 +23,11 @@
* SOFTWARE. * SOFTWARE.
*/ */
package me.lucko.luckperms.bukkit; package me.lucko.luckperms.bukkit.listeners;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.bukkit.model.Injector; import me.lucko.luckperms.bukkit.model.Injector;
import me.lucko.luckperms.bukkit.model.LPPermissible; import me.lucko.luckperms.bukkit.model.LPPermissible;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
@ -39,11 +40,8 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginEnableEvent;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
@ -52,7 +50,7 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor @RequiredArgsConstructor
public class BukkitListener implements Listener { public class BukkitConnectionListener implements Listener {
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
private final Set<UUID> deniedAsyncLogin = Collections.synchronizedSet(new HashSet<>()); private final Set<UUID> deniedAsyncLogin = Collections.synchronizedSet(new HashSet<>());
@ -225,33 +223,4 @@ public class BukkitListener implements Listener {
plugin.getUserManager().scheduleUnload(player.getUniqueId()); plugin.getUserManager().scheduleUnload(player.getUniqueId());
} }
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
if (plugin.getConfiguration().get(ConfigKeys.OPS_ENABLED)) {
return;
}
String s = e.getMessage().substring(1).toLowerCase()
.replace("bukkit:", "")
.replace("spigot:", "")
.replace("minecraft:", "");
if (s.equals("op") || s.startsWith("op ") || s.equals("deop") || s.startsWith("deop ")) {
e.setCancelled(true);
e.getPlayer().sendMessage(Message.OP_DISABLED.asString(plugin.getLocaleManager()));
}
}
@EventHandler
public void onPluginEnable(PluginEnableEvent e) {
if (e.getPlugin().getName().equalsIgnoreCase("Vault")) {
plugin.tryVaultHook(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onWorldChange(PlayerChangedWorldEvent e) {
plugin.getContextManager().invalidateCache(e.getPlayer());
plugin.refreshAutoOp(plugin.getUserManager().getIfLoaded(e.getPlayer().getUniqueId()), e.getPlayer());
}
} }

View File

@ -0,0 +1,100 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* 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.bukkit.listeners;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.RemoteServerCommandEvent;
import org.bukkit.event.server.ServerCommandEvent;
@RequiredArgsConstructor
public class BukkitPlatformListener implements Listener {
private final LPBukkitPlugin plugin;
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
handleCommand(e.getPlayer(), e.getMessage().toLowerCase(), e);
}
@EventHandler
public void onServerCommand(ServerCommandEvent e) {
handleCommand(e.getSender(), e.getCommand().toLowerCase(), e);
}
@EventHandler
public void onRemoteServerCommand(RemoteServerCommandEvent e) {
handleCommand(e.getSender(), e.getCommand().toLowerCase(), e);
}
private void handleCommand(CommandSender sender, String s, Cancellable event) {
if (s.isEmpty()) {
return;
}
if (plugin.getConfiguration().get(ConfigKeys.OPS_ENABLED)) {
return;
}
if (s.charAt(0) == '/') {
s = s.substring(1);
}
if (s.startsWith("minecraft:")) {
s = s.substring("minecraft:".length());
}
if (s.equals("op") || s.startsWith("op ") || s.equals("deop") || s.startsWith("deop ")) {
event.setCancelled(true);
sender.sendMessage(Message.OP_DISABLED.asString(plugin.getLocaleManager()));
}
}
@EventHandler
public void onPluginEnable(PluginEnableEvent e) {
if (e.getPlugin().getName().equalsIgnoreCase("Vault")) {
plugin.tryVaultHook(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onWorldChange(PlayerChangedWorldEvent e) {
plugin.getContextManager().invalidateCache(e.getPlayer());
plugin.refreshAutoOp(plugin.getUserManager().getIfLoaded(e.getPlayer().getUniqueId()), e.getPlayer());
}
}

View File

@ -26,7 +26,7 @@
package me.lucko.luckperms.bukkit.messaging; package me.lucko.luckperms.bukkit.messaging;
import me.lucko.luckperms.bukkit.LPBukkitPlugin; import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.MessagingFactory; import me.lucko.luckperms.common.messaging.MessagingFactory;
public class BukkitMessagingFactory extends MessagingFactory<LPBukkitPlugin> { public class BukkitMessagingFactory extends MessagingFactory<LPBukkitPlugin> {
@ -35,7 +35,7 @@ public class BukkitMessagingFactory extends MessagingFactory<LPBukkitPlugin> {
} }
@Override @Override
protected InternalMessagingService getServiceFor(String messagingType) { protected ExtendedMessagingService getServiceFor(String messagingType) {
if (messagingType.equals("bungee")) { if (messagingType.equals("bungee")) {
BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin()); BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin());
bungeeMessaging.init(); bungeeMessaging.init();

View File

@ -32,6 +32,7 @@ import com.google.common.io.ByteStreams;
import me.lucko.luckperms.bukkit.LPBukkitPlugin; import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.common.messaging.AbstractMessagingService; import me.lucko.luckperms.common.messaging.AbstractMessagingService;
import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener; import org.bukkit.plugin.messaging.PluginMessageListener;
@ -40,7 +41,7 @@ import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collection; import java.util.Collection;
/** /**
* An implementation of {@link me.lucko.luckperms.api.MessagingService} using the plugin messaging channels. * An implementation of {@link ExtendedMessagingService} using the plugin messaging channels.
*/ */
public class BungeeMessagingService extends AbstractMessagingService implements PluginMessageListener { public class BungeeMessagingService extends AbstractMessagingService implements PluginMessageListener {
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
@ -62,7 +63,7 @@ public class BungeeMessagingService extends AbstractMessagingService implements
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
@ -77,7 +78,7 @@ public class BungeeMessagingService extends AbstractMessagingService implements
byte[] data = out.toByteArray(); byte[] data = out.toByteArray();
p.sendPluginMessage(plugin, channel, data); p.sendPluginMessage(plugin, CHANNEL, data);
cancel(); cancel();
} }
}.runTaskTimer(plugin, 1L, 100L); }.runTaskTimer(plugin, 1L, 100L);
@ -92,6 +93,6 @@ public class BungeeMessagingService extends AbstractMessagingService implements
ByteArrayDataInput in = ByteStreams.newDataInput(bytes); ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
String msg = in.readUTF(); String msg = in.readUTF();
onMessage(s, msg, null); onMessage(msg, null);
} }
} }

View File

@ -27,6 +27,7 @@ package me.lucko.luckperms.bukkit.messaging;
import me.lucko.luckperms.bukkit.LPBukkitPlugin; import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.common.messaging.AbstractMessagingService; import me.lucko.luckperms.common.messaging.AbstractMessagingService;
import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import lilypad.client.connect.api.Connect; import lilypad.client.connect.api.Connect;
import lilypad.client.connect.api.event.EventListener; import lilypad.client.connect.api.event.EventListener;
@ -38,7 +39,7 @@ import java.io.UnsupportedEncodingException;
import java.util.Collections; import java.util.Collections;
/** /**
* An implementation of {@link me.lucko.luckperms.api.MessagingService} using LilyPad. * An implementation of {@link ExtendedMessagingService} using LilyPad.
*/ */
public class LilyPadMessagingService extends AbstractMessagingService { public class LilyPadMessagingService extends AbstractMessagingService {
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
@ -60,11 +61,11 @@ public class LilyPadMessagingService extends AbstractMessagingService {
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
MessageRequest request; MessageRequest request;
try { try {
request = new MessageRequest(Collections.emptyList(), channel, message); request = new MessageRequest(Collections.emptyList(), CHANNEL, message);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
@ -79,12 +80,17 @@ public class LilyPadMessagingService extends AbstractMessagingService {
@EventListener @EventListener
public void onMessage(MessageEvent event) { public void onMessage(MessageEvent event) {
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
try { try {
String channel = event.getChannel(); String channel = event.getChannel();
if (!channel.equals(CHANNEL)) {
return;
}
String message = event.getMessageAsString(); String message = event.getMessageAsString();
onMessage(channel, message, null); onMessage(message, null);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -73,7 +73,7 @@ public class LPPermissible extends PermissibleBase {
private final User user; private final User user;
// the player this permissible is injected into. // the player this permissible is injected into.
private final Player parent; private final Player player;
// the luckperms plugin instance // the luckperms plugin instance
private final LPBukkitPlugin plugin; private final LPBukkitPlugin plugin;
@ -92,10 +92,10 @@ public class LPPermissible extends PermissibleBase {
// this collection is only modified by the attachments themselves // this collection is only modified by the attachments themselves
final Set<LPPermissionAttachment> attachments = ConcurrentHashMap.newKeySet(); final Set<LPPermissionAttachment> attachments = ConcurrentHashMap.newKeySet();
public LPPermissible(@NonNull Player parent, @NonNull User user, @NonNull LPBukkitPlugin plugin) { public LPPermissible(@NonNull Player player, @NonNull User user, @NonNull LPBukkitPlugin plugin) {
super(parent); super(player);
this.user = user; this.user = user;
this.parent = parent; this.player = player;
this.plugin = plugin; this.plugin = plugin;
this.subscriptions = new SubscriptionManager(this); this.subscriptions = new SubscriptionManager(this);
} }
@ -148,7 +148,7 @@ public class LPPermissible extends PermissibleBase {
return; return;
} }
plugin.doAsync(this::updateSubscriptions); plugin.getScheduler().doAsync(this::updateSubscriptions);
} }
/** /**
@ -166,7 +166,7 @@ public class LPPermissible extends PermissibleBase {
// include defaults, if enabled. // include defaults, if enabled.
if (plugin.getConfiguration().get(ConfigKeys.APPLY_BUKKIT_DEFAULT_PERMISSIONS)) { if (plugin.getConfiguration().get(ConfigKeys.APPLY_BUKKIT_DEFAULT_PERMISSIONS)) {
if (parent.isOp()) { if (player.isOp()) {
ent.addAll(plugin.getDefaultsProvider().getOpDefaults().keySet()); ent.addAll(plugin.getDefaultsProvider().getOpDefaults().keySet());
} else { } else {
ent.addAll(plugin.getDefaultsProvider().getNonOpDefaults().keySet()); ent.addAll(plugin.getDefaultsProvider().getNonOpDefaults().keySet());
@ -180,7 +180,7 @@ public class LPPermissible extends PermissibleBase {
* Unsubscribes from all permissions asynchronously * Unsubscribes from all permissions asynchronously
*/ */
public void unsubscribeFromAllAsync() { public void unsubscribeFromAllAsync() {
plugin.doAsync(this::unsubscribeFromAll); plugin.getScheduler().doAsync(this::unsubscribeFromAll);
} }
/** /**
@ -208,12 +208,12 @@ public class LPPermissible extends PermissibleBase {
* @return the calculated contexts for the player. * @return the calculated contexts for the player.
*/ */
public Contexts calculateContexts() { public Contexts calculateContexts() {
return plugin.getContextManager().getApplicableContexts(parent); return plugin.getContextManager().getApplicableContexts(player);
} }
@Override @Override
public void setOp(boolean value) { public void setOp(boolean value) {
parent.setOp(value); player.setOp(value);
} }
@Override @Override
@ -221,7 +221,7 @@ public class LPPermissible extends PermissibleBase {
Set<PermissionAttachmentInfo> perms = new HashSet<>(); Set<PermissionAttachmentInfo> perms = new HashSet<>();
perms.addAll( perms.addAll(
user.getUserData().getPermissionData(calculateContexts()).getImmutableBacking().entrySet().stream() user.getUserData().getPermissionData(calculateContexts()).getImmutableBacking().entrySet().stream()
.map(e -> new PermissionAttachmentInfo(parent, e.getKey(), null, e.getValue())) .map(e -> new PermissionAttachmentInfo(player, e.getKey(), null, e.getValue()))
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
return perms; return perms;
@ -250,7 +250,7 @@ public class LPPermissible extends PermissibleBase {
LPPermissionAttachment ret = addAttachment(plugin); LPPermissionAttachment ret = addAttachment(plugin);
if (getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(plugin, ret::remove, ticks) == -1) { if (getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(plugin, ret::remove, ticks) == -1) {
ret.remove(); ret.remove();
throw new RuntimeException("Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1"); throw new RuntimeException("Could not add PermissionAttachment to " + player + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1");
} }
return ret; return ret;
} }

View File

@ -57,7 +57,9 @@ public class SubscriptionManager {
// we compare changes to avoid unnecessary time wasted on the main thread mutating this data. // we compare changes to avoid unnecessary time wasted on the main thread mutating this data.
// the changes can be calculated here async, and then only the needed changes can be applied. // the changes can be calculated here async, and then only the needed changes can be applied.
Map.Entry<Set<String>, Set<String>> changes = compareSets(newPerms, currentSubscriptions); Map.Entry<Set<String>, Set<String>> changes = compareSets(newPerms, currentSubscriptions);
permissible.getPlugin().doSync(new SubscriptionUpdateTask(permissible, changes.getKey(), changes.getValue())); if (!changes.getKey().isEmpty() || !changes.getValue().isEmpty()) {
permissible.getPlugin().getScheduler().doSync(new SubscriptionUpdateTask(permissible, changes.getKey(), changes.getValue()));
}
this.currentSubscriptions = newPerms; this.currentSubscriptions = newPerms;
} }
@ -71,10 +73,10 @@ public class SubscriptionManager {
@Override @Override
public void run() { public void run() {
for (String s : toAdd) { for (String s : toAdd) {
permissible.getPlugin().getServer().getPluginManager().subscribeToPermission(s, permissible.getParent()); permissible.getPlugin().getServer().getPluginManager().subscribeToPermission(s, permissible.getPlayer());
} }
for (String s : toRemove) { for (String s : toRemove) {
permissible.getPlugin().getServer().getPluginManager().unsubscribeFromPermission(s, permissible.getParent()); permissible.getPlugin().getServer().getPluginManager().unsubscribeFromPermission(s, permissible.getPlayer());
} }
} }
} }

View File

@ -0,0 +1,55 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* 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.bukkit.processors;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import java.util.HashSet;
import java.util.Set;
/**
* Performs the initial setup for Bukkit permission processors
*/
@RequiredArgsConstructor
public class BukkitProcessorsSetupTask implements Runnable {
private final LPBukkitPlugin plugin;
@Override
public void run() {
plugin.getDefaultsProvider().refresh();
plugin.getChildPermissionProvider().setup();
Set<String> perms = new HashSet<>();
plugin.getServer().getPluginManager().getPermissions().forEach(p -> {
perms.add(p.getName());
perms.addAll(p.getChildren().keySet());
});
perms.forEach(p -> plugin.getPermissionVault().offer(p));
}
}

View File

@ -29,19 +29,23 @@ import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import me.lucko.luckperms.common.commands.CommandManager; import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.commands.utils.Util;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.TabExecutor; import net.md_5.bungee.api.plugin.TabExecutor;
import java.util.Arrays; import java.util.List;
public class BungeeCommandExecutor extends Command implements TabExecutor {
private static final Splitter ARGUMENT_SPLITTER = Splitter.on(CommandManager.COMMAND_SEPARATOR_PATTERN).omitEmptyStrings();
private static final Joiner ARGUMENT_JOINER = Joiner.on(' ');
public class BungeeCommand extends Command implements TabExecutor {
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;
private final CommandManager manager; private final CommandManager manager;
BungeeCommand(LPBungeePlugin plugin, CommandManager manager) { BungeeCommandExecutor(LPBungeePlugin plugin, CommandManager manager) {
super("luckpermsbungee", null, "lpb", "bperm", "bperms", "bpermission", "bpermissions"); super("luckpermsbungee", null, "lpb", "bperm", "bperms", "bpermission", "bpermissions");
this.plugin = plugin; this.plugin = plugin;
this.manager = manager; this.manager = manager;
@ -49,15 +53,17 @@ public class BungeeCommand extends Command implements TabExecutor {
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
manager.onCommand( Sender lpSender = plugin.getSenderFactory().wrap(sender);
plugin.getSenderFactory().wrap(sender), List<String> arguments = Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(ARGUMENT_JOINER.join(args)));
"lpb",
Util.stripQuotes(Splitter.on(CommandManager.COMMAND_SEPARATOR_PATTERN).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))) manager.onCommand(lpSender, "lpb", arguments);
);
} }
@Override @Override
public Iterable<String> onTabComplete(CommandSender sender, String[] args) { public Iterable<String> onTabComplete(CommandSender sender, String[] args) {
return manager.onTabComplete(plugin.getSenderFactory().wrap(sender), Arrays.asList(args)); Sender lpSender = plugin.getSenderFactory().wrap(sender);
List<String> arguments = Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(ARGUMENT_JOINER.join(args)));
return manager.onTabComplete(lpSender, arguments);
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.bungee;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.common.config.AbstractConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.ConfigurationProvider;
@ -45,7 +45,7 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
@RequiredArgsConstructor @RequiredArgsConstructor
public class BungeeConfig extends AbstractConfiguration { public class BungeeConfigAdapter implements ConfigurationAdapter {
@Getter @Getter
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;

View File

@ -25,7 +25,7 @@
package me.lucko.luckperms.bungee; package me.lucko.luckperms.bungee;
import me.lucko.luckperms.common.plugin.LuckPermsScheduler; import me.lucko.luckperms.common.plugin.SchedulerAdapter;
import net.md_5.bungee.api.scheduler.ScheduledTask; import net.md_5.bungee.api.scheduler.ScheduledTask;
@ -34,13 +34,13 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class LPBungeeScheduler implements LuckPermsScheduler { public class BungeeSchedulerAdapter implements SchedulerAdapter {
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;
private final Executor asyncExecutor; private final Executor asyncExecutor;
private final Set<ScheduledTask> tasks = ConcurrentHashMap.newKeySet(); private final Set<ScheduledTask> tasks = ConcurrentHashMap.newKeySet();
public LPBungeeScheduler(LPBungeePlugin plugin) { public BungeeSchedulerAdapter(LPBungeePlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
this.asyncExecutor = r -> plugin.getProxy().getScheduler().runAsync(plugin, r); this.asyncExecutor = r -> plugin.getProxy().getScheduler().runAsync(plugin, r);
} }

View File

@ -33,6 +33,8 @@ import me.lucko.luckperms.api.PlatformType;
import me.lucko.luckperms.bungee.calculators.BungeeCalculatorFactory; import me.lucko.luckperms.bungee.calculators.BungeeCalculatorFactory;
import me.lucko.luckperms.bungee.contexts.BackendServerCalculator; import me.lucko.luckperms.bungee.contexts.BackendServerCalculator;
import me.lucko.luckperms.bungee.contexts.BungeeContextManager; import me.lucko.luckperms.bungee.contexts.BungeeContextManager;
import me.lucko.luckperms.bungee.listeners.BungeeConnectionListener;
import me.lucko.luckperms.bungee.listeners.BungeePermissionCheckListener;
import me.lucko.luckperms.bungee.messaging.BungeeMessagingFactory; import me.lucko.luckperms.bungee.messaging.BungeeMessagingFactory;
import me.lucko.luckperms.bungee.util.RedisBungeeUtil; import me.lucko.luckperms.bungee.util.RedisBungeeUtil;
import me.lucko.luckperms.common.actionlog.LogDispatcher; import me.lucko.luckperms.common.actionlog.LogDispatcher;
@ -44,6 +46,7 @@ import me.lucko.luckperms.common.caching.handlers.CachedStateManager;
import me.lucko.luckperms.common.calculators.CalculatorFactory; import me.lucko.luckperms.common.calculators.CalculatorFactory;
import me.lucko.luckperms.common.commands.CommandManager; import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.config.AbstractConfiguration;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.LuckPermsConfiguration;
import me.lucko.luckperms.common.contexts.ContextManager; import me.lucko.luckperms.common.contexts.ContextManager;
@ -60,10 +63,10 @@ import me.lucko.luckperms.common.managers.GenericUserManager;
import me.lucko.luckperms.common.managers.GroupManager; import me.lucko.luckperms.common.managers.GroupManager;
import me.lucko.luckperms.common.managers.TrackManager; import me.lucko.luckperms.common.managers.TrackManager;
import me.lucko.luckperms.common.managers.UserManager; import me.lucko.luckperms.common.managers.UserManager;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.plugin.LuckPermsScheduler; import me.lucko.luckperms.common.plugin.SchedulerAdapter;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.storage.StorageFactory; import me.lucko.luckperms.common.storage.StorageFactory;
import me.lucko.luckperms.common.storage.StorageType; import me.lucko.luckperms.common.storage.StorageType;
@ -81,12 +84,11 @@ import net.md_5.bungee.api.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Stream;
/** /**
* LuckPerms implementation for the BungeeCord API. * LuckPerms implementation for the BungeeCord API.
@ -95,7 +97,7 @@ import java.util.stream.Collectors;
public class LPBungeePlugin extends Plugin implements LuckPermsPlugin { public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
private long startTime; private long startTime;
private LuckPermsScheduler scheduler; private SchedulerAdapter scheduler;
private CommandManager commandManager; private CommandManager commandManager;
private LuckPermsConfiguration configuration; private LuckPermsConfiguration configuration;
private UserManager userManager; private UserManager userManager;
@ -103,7 +105,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
private TrackManager trackManager; private TrackManager trackManager;
private Storage storage; private Storage storage;
private FileWatcher fileWatcher = null; private FileWatcher fileWatcher = null;
private InternalMessagingService messagingService = null; private ExtendedMessagingService messagingService = null;
private UuidCache uuidCache; private UuidCache uuidCache;
private ApiProvider apiProvider; private ApiProvider apiProvider;
private Logger log; private Logger log;
@ -121,7 +123,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
@Override @Override
public void onLoad() { public void onLoad() {
// setup minimal functionality in order to load initial dependencies // setup minimal functionality in order to load initial dependencies
scheduler = new LPBungeeScheduler(this); scheduler = new BungeeSchedulerAdapter(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new BungeeSenderFactory(this); senderFactory = new BungeeSenderFactory(this);
log = new SenderLogger(this, getConsoleSender()); log = new SenderLogger(this, getConsoleSender());
@ -138,15 +140,15 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
logDispatcher = new LogDispatcher(this); logDispatcher = new LogDispatcher(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new BungeeConfig(this); configuration = new AbstractConfiguration(this, new BungeeConfigAdapter(this));
configuration.init(); configuration.init();
configuration.loadAll();
Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2); Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2);
DependencyManager.loadStorageDependencies(this, storageTypes); DependencyManager.loadStorageDependencies(this, storageTypes);
// register events // register events
getProxy().getPluginManager().registerListener(this, new BungeeListener(this)); getProxy().getPluginManager().registerListener(this, new BungeeConnectionListener(this));
getProxy().getPluginManager().registerListener(this, new BungeePermissionCheckListener(this));
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
@ -168,7 +170,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
// register commands // register commands
commandManager = new CommandManager(this); commandManager = new CommandManager(this);
getProxy().getPluginManager().registerCommand(this, new BungeeCommand(this, commandManager)); getProxy().getPluginManager().registerCommand(this, new BungeeCommandExecutor(this, commandManager));
// disable the default Bungee /perms command so it gets handled by the Bukkit plugin // disable the default Bungee /perms command so it gets handled by the Bukkit plugin
getProxy().getDisabledCommands().add("perms"); getProxy().getDisabledCommands().add("perms");
@ -237,6 +239,15 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
getLog().info("Goodbye!"); getLog().info("Goodbye!");
} }
@Override
public Optional<ExtendedMessagingService> getMessagingService() {
return Optional.ofNullable(messagingService);
}
public Optional<FileWatcher> getFileWatcher() {
return Optional.ofNullable(fileWatcher);
}
@Override @Override
public String getVersion() { public String getVersion() {
return getDescription().getVersion(); return getDescription().getVersion();
@ -300,13 +311,13 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
} }
@Override @Override
public List<String> getPlayerList() { public Stream<String> getPlayerList() {
return getProxy().getPlayers().stream().map(ProxiedPlayer::getName).collect(Collectors.toList()); return getProxy().getPlayers().stream().map(ProxiedPlayer::getName);
} }
@Override @Override
public Set<UUID> getOnlinePlayers() { public Stream<UUID> getOnlinePlayers() {
return getProxy().getPlayers().stream().map(ProxiedPlayer::getUniqueId).collect(Collectors.toSet()); return getProxy().getPlayers().stream().map(ProxiedPlayer::getUniqueId);
} }
@Override @Override
@ -316,10 +327,11 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getOnlineSenders() { public Stream<Sender> getOnlineSenders() {
return getProxy().getPlayers().stream() return Stream.concat(
.map(p -> getSenderFactory().wrap(p)) Stream.of(getConsoleSender()),
.collect(Collectors.toList()); getProxy().getPlayers().stream().map(p -> getSenderFactory().wrap(p))
);
} }
@Override @Override

View File

@ -61,11 +61,8 @@ public class BungeeCalculatorFactory extends AbstractCalculatorFactory {
processors.add(new WildcardProcessor()); processors.add(new WildcardProcessor());
} }
return registerCalculator(new PermissionCalculator( PermissionCalculatorMetadata meta = PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts());
plugin, return registerCalculator(new PermissionCalculator(plugin, meta, processors.build()));
PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts()),
processors.build()
));
} }
@Override @Override

View File

@ -23,24 +23,20 @@
* SOFTWARE. * SOFTWARE.
*/ */
package me.lucko.luckperms.bungee; package me.lucko.luckperms.bungee.listeners;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.api.Contexts; import me.lucko.luckperms.bungee.LPBungeePlugin;
import me.lucko.luckperms.api.Tristate;
import me.lucko.luckperms.bungee.event.TristateCheckEvent;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message; import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.utils.LoginHelper; import me.lucko.luckperms.common.utils.LoginHelper;
import me.lucko.luckperms.common.verbose.CheckOrigin;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.LoginEvent; import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PermissionCheckEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Listener;
@ -50,7 +46,7 @@ import net.md_5.bungee.event.EventPriority;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor @RequiredArgsConstructor
public class BungeeListener implements Listener { public class BungeeConnectionListener implements Listener {
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
@ -91,7 +87,7 @@ public class BungeeListener implements Listener {
} }
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
plugin.getUniqueConnections().add(c.getUniqueId()); plugin.getUniqueConnections().add(c.getUniqueId());
/* Actually process the login for the connection. /* Actually process the login for the connection.
@ -163,50 +159,4 @@ public class BungeeListener implements Listener {
plugin.getUserManager().scheduleUnload(e.getPlayer().getUniqueId()); plugin.getUserManager().scheduleUnload(e.getPlayer().getUniqueId());
} }
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerPermissionCheck(PermissionCheckEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
}
final ProxiedPlayer player = ((ProxiedPlayer) e.getSender());
User user = plugin.getUserManager().getIfLoaded(plugin.getUuidCache().getUUID(player.getUniqueId()));
if (user == null) {
e.setHasPermission(false);
return;
}
Contexts contexts = plugin.getContextManager().getApplicableContexts(player);
Tristate result = user.getUserData().getPermissionData(contexts).getPermissionValue(e.getPermission(), CheckOrigin.PLATFORM_PERMISSION_CHECK);
if (result == Tristate.UNDEFINED && plugin.getConfiguration().get(ConfigKeys.APPLY_BUNGEE_CONFIG_PERMISSIONS)) {
return; // just use the result provided by the proxy when the event was created
}
e.setHasPermission(result.asBoolean());
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerTristateCheck(TristateCheckEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
}
final ProxiedPlayer player = ((ProxiedPlayer) e.getSender());
User user = plugin.getUserManager().getIfLoaded(plugin.getUuidCache().getUUID(player.getUniqueId()));
if (user == null) {
e.setResult(Tristate.UNDEFINED);
return;
}
Contexts contexts = plugin.getContextManager().getApplicableContexts(player);
Tristate result = user.getUserData().getPermissionData(contexts).getPermissionValue(e.getPermission(), CheckOrigin.PLATFORM_LOOKUP_CHECK);
if (result == Tristate.UNDEFINED && plugin.getConfiguration().get(ConfigKeys.APPLY_BUNGEE_CONFIG_PERMISSIONS)) {
return; // just use the result provided by the proxy when the event was created
}
e.setResult(result);
}
} }

View File

@ -0,0 +1,93 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* 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.bungee.listeners;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.api.Contexts;
import me.lucko.luckperms.api.Tristate;
import me.lucko.luckperms.bungee.LPBungeePlugin;
import me.lucko.luckperms.bungee.event.TristateCheckEvent;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.verbose.CheckOrigin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PermissionCheckEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
@RequiredArgsConstructor
public class BungeePermissionCheckListener implements Listener {
private final LPBungeePlugin plugin;
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerPermissionCheck(PermissionCheckEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
}
final ProxiedPlayer player = ((ProxiedPlayer) e.getSender());
User user = plugin.getUserManager().getIfLoaded(plugin.getUuidCache().getUUID(player.getUniqueId()));
if (user == null) {
e.setHasPermission(false);
return;
}
Contexts contexts = plugin.getContextManager().getApplicableContexts(player);
Tristate result = user.getUserData().getPermissionData(contexts).getPermissionValue(e.getPermission(), CheckOrigin.PLATFORM_PERMISSION_CHECK);
if (result == Tristate.UNDEFINED && plugin.getConfiguration().get(ConfigKeys.APPLY_BUNGEE_CONFIG_PERMISSIONS)) {
return; // just use the result provided by the proxy when the event was created
}
e.setHasPermission(result.asBoolean());
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerTristateCheck(TristateCheckEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
}
final ProxiedPlayer player = ((ProxiedPlayer) e.getSender());
User user = plugin.getUserManager().getIfLoaded(plugin.getUuidCache().getUUID(player.getUniqueId()));
if (user == null) {
e.setResult(Tristate.UNDEFINED);
return;
}
Contexts contexts = plugin.getContextManager().getApplicableContexts(player);
Tristate result = user.getUserData().getPermissionData(contexts).getPermissionValue(e.getPermission(), CheckOrigin.PLATFORM_LOOKUP_CHECK);
if (result == Tristate.UNDEFINED && plugin.getConfiguration().get(ConfigKeys.APPLY_BUNGEE_CONFIG_PERMISSIONS)) {
return; // just use the result provided by the proxy when the event was created
}
e.setResult(result);
}
}

View File

@ -26,7 +26,7 @@
package me.lucko.luckperms.bungee.messaging; package me.lucko.luckperms.bungee.messaging;
import me.lucko.luckperms.bungee.LPBungeePlugin; import me.lucko.luckperms.bungee.LPBungeePlugin;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.MessagingFactory; import me.lucko.luckperms.common.messaging.MessagingFactory;
public class BungeeMessagingFactory extends MessagingFactory<LPBungeePlugin> { public class BungeeMessagingFactory extends MessagingFactory<LPBungeePlugin> {
@ -35,7 +35,7 @@ public class BungeeMessagingFactory extends MessagingFactory<LPBungeePlugin> {
} }
@Override @Override
protected InternalMessagingService getServiceFor(String messagingType) { protected ExtendedMessagingService getServiceFor(String messagingType) {
if (messagingType.equals("bungee")) { if (messagingType.equals("bungee")) {
BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin()); BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin());
bungeeMessaging.init(); bungeeMessaging.init();

View File

@ -31,6 +31,7 @@ import com.google.common.io.ByteStreams;
import me.lucko.luckperms.bungee.LPBungeePlugin; import me.lucko.luckperms.bungee.LPBungeePlugin;
import me.lucko.luckperms.common.messaging.AbstractMessagingService; import me.lucko.luckperms.common.messaging.AbstractMessagingService;
import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -39,7 +40,7 @@ import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
/** /**
* An implementation of {@link me.lucko.luckperms.api.MessagingService} using the plugin messaging channels. * An implementation of {@link ExtendedMessagingService} using the plugin messaging channels.
*/ */
public class BungeeMessagingService extends AbstractMessagingService implements Listener { public class BungeeMessagingService extends AbstractMessagingService implements Listener {
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;
@ -60,7 +61,7 @@ public class BungeeMessagingService extends AbstractMessagingService implements
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
ByteArrayDataOutput out = ByteStreams.newDataOutput(); ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(message); out.writeUTF(message);
@ -68,7 +69,7 @@ public class BungeeMessagingService extends AbstractMessagingService implements
byte[] data = out.toByteArray(); byte[] data = out.toByteArray();
for (ServerInfo server : plugin.getProxy().getServers().values()) { for (ServerInfo server : plugin.getProxy().getServers().values()) {
server.sendData(channel, data, true); server.sendData(CHANNEL, data, true);
} }
} }
@ -87,9 +88,9 @@ public class BungeeMessagingService extends AbstractMessagingService implements
ByteArrayDataInput in = ByteStreams.newDataInput(e.getData()); ByteArrayDataInput in = ByteStreams.newDataInput(e.getData());
String msg = in.readUTF(); String msg = in.readUTF();
onMessage(e.getTag(), msg, u -> { onMessage(msg, u -> {
// Forward to other servers // Forward to other servers
plugin.doAsync(() -> sendMessage(CHANNEL, u)); plugin.getScheduler().doAsync(() -> sendMessage(u));
}); });
} }
} }

View File

@ -31,12 +31,13 @@ import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
import me.lucko.luckperms.bungee.LPBungeePlugin; import me.lucko.luckperms.bungee.LPBungeePlugin;
import me.lucko.luckperms.common.messaging.AbstractMessagingService; import me.lucko.luckperms.common.messaging.AbstractMessagingService;
import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
/** /**
* An implementation of {@link me.lucko.luckperms.api.MessagingService} using Redis, via RedisBungee's API. * An implementation of {@link ExtendedMessagingService} using Redis, via RedisBungee's API.
*/ */
public class RedisBungeeMessagingService extends AbstractMessagingService implements Listener { public class RedisBungeeMessagingService extends AbstractMessagingService implements Listener {
private final LPBungeePlugin plugin; private final LPBungeePlugin plugin;
@ -63,12 +64,16 @@ public class RedisBungeeMessagingService extends AbstractMessagingService implem
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
redisBungee.sendChannelMessage(channel, message); redisBungee.sendChannelMessage(CHANNEL, message);
} }
@EventHandler @EventHandler
public void onMessage(PubSubMessageEvent e) { public void onMessage(PubSubMessageEvent e) {
onMessage(e.getChannel(), e.getMessage(), null); if (!e.getChannel().equals(CHANNEL)) {
return;
}
onMessage(e.getMessage(), null);
} }
} }

View File

@ -34,11 +34,10 @@ import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.constants.CommandPermission; import me.lucko.luckperms.common.constants.CommandPermission;
import me.lucko.luckperms.common.locale.Message; import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.NoopMessagingService;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import java.util.List; import java.util.Optional;
@RequiredArgsConstructor @RequiredArgsConstructor
public class LogDispatcher { public class LogDispatcher {
@ -55,18 +54,15 @@ public class LogDispatcher {
return; return;
} }
InternalMessagingService messagingService = plugin.getMessagingService(); Optional<ExtendedMessagingService> messagingService = plugin.getMessagingService();
if (!sender.isImport() && !(messagingService instanceof NoopMessagingService)) { if (!sender.isImport() && messagingService.isPresent()) {
messagingService.pushLog(entry); messagingService.get().pushLog(entry);
} }
if (!plugin.getApiProvider().getEventFactory().handleLogBroadcast(!plugin.getConfiguration().get(ConfigKeys.LOG_NOTIFY), entry, LogBroadcastEvent.Origin.LOCAL)) { if (!plugin.getApiProvider().getEventFactory().handleLogBroadcast(!plugin.getConfiguration().get(ConfigKeys.LOG_NOTIFY), entry, LogBroadcastEvent.Origin.LOCAL)) {
final String msg = entry.getFormatted(); final String msg = entry.getFormatted();
List<Sender> senders = plugin.getOnlineSenders(); plugin.getOnlineSenders()
senders.add(plugin.getConsoleSender());
senders.stream()
.filter(CommandPermission.LOG_NOTIFY::isAuthorized) .filter(CommandPermission.LOG_NOTIFY::isAuthorized)
.filter(s -> !LogNotify.isIgnoring(plugin, s.getUuid())) .filter(s -> !LogNotify.isIgnoring(plugin, s.getUuid()))
.filter(s -> !s.getUuid().equals(sender.getUuid())) .filter(s -> !s.getUuid().equals(sender.getUuid()))
@ -82,10 +78,7 @@ public class LogDispatcher {
if (!plugin.getApiProvider().getEventFactory().handleLogBroadcast(!plugin.getConfiguration().get(ConfigKeys.LOG_NOTIFY), entry, LogBroadcastEvent.Origin.REMOTE)) { if (!plugin.getApiProvider().getEventFactory().handleLogBroadcast(!plugin.getConfiguration().get(ConfigKeys.LOG_NOTIFY), entry, LogBroadcastEvent.Origin.REMOTE)) {
final String msg = entry.getFormatted(); final String msg = entry.getFormatted();
List<Sender> senders = plugin.getOnlineSenders(); plugin.getOnlineSenders()
senders.add(plugin.getConsoleSender());
senders.stream()
.filter(CommandPermission.LOG_NOTIFY::isAuthorized) .filter(CommandPermission.LOG_NOTIFY::isAuthorized)
.filter(s -> !LogNotify.isIgnoring(plugin, s.getUuid())) .filter(s -> !LogNotify.isIgnoring(plugin, s.getUuid()))
.forEach(s -> Message.LOG.send(s, msg)); .forEach(s -> Message.LOG.send(s, msg));

View File

@ -48,8 +48,6 @@ import me.lucko.luckperms.common.api.delegates.NodeFactoryDelegate;
import me.lucko.luckperms.common.api.delegates.UserDelegate; import me.lucko.luckperms.common.api.delegates.UserDelegate;
import me.lucko.luckperms.common.event.EventFactory; import me.lucko.luckperms.common.event.EventFactory;
import me.lucko.luckperms.common.event.LuckPermsEventBus; import me.lucko.luckperms.common.event.LuckPermsEventBus;
import me.lucko.luckperms.common.messaging.InternalMessagingService;
import me.lucko.luckperms.common.messaging.NoopMessagingService;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.references.UserIdentifier; import me.lucko.luckperms.common.references.UserIdentifier;
@ -57,6 +55,7 @@ import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -113,8 +112,7 @@ public class ApiProvider implements LuckPermsApi {
@Override @Override
public Optional<MessagingService> getMessagingService() { public Optional<MessagingService> getMessagingService() {
InternalMessagingService service = plugin.getMessagingService(); return plugin.getMessagingService().map(Function.identity());
return service instanceof NoopMessagingService ? Optional.empty() : Optional.of(service);
} }
@Override @Override

View File

@ -32,7 +32,7 @@ public class UpdateTaskBuffer extends BufferedRequest<Void> {
private final LuckPermsPlugin plugin; private final LuckPermsPlugin plugin;
public UpdateTaskBuffer(LuckPermsPlugin plugin) { public UpdateTaskBuffer(LuckPermsPlugin plugin) {
super(250L, 50L, plugin::doAsync); super(250L, 50L, plugin.getScheduler().async());
this.plugin = plugin; this.plugin = plugin;
} }

View File

@ -36,8 +36,7 @@ import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.constants.CommandPermission; import me.lucko.luckperms.common.constants.CommandPermission;
import me.lucko.luckperms.common.locale.LocalizedSpec; import me.lucko.luckperms.common.locale.LocalizedSpec;
import me.lucko.luckperms.common.locale.Message; import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.NoopMessagingService;
import me.lucko.luckperms.common.model.Group; import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.model.Track; import me.lucko.luckperms.common.model.Track;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
@ -50,6 +49,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -182,9 +182,9 @@ public abstract class SubCommand<T> extends Command<T, Void> {
} }
if (!sender.isImport()) { if (!sender.isImport()) {
InternalMessagingService messagingService = plugin.getMessagingService(); Optional<ExtendedMessagingService> messagingService = plugin.getMessagingService();
if (!(messagingService instanceof NoopMessagingService) && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) { if (messagingService.isPresent() && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) {
messagingService.getUpdateBuffer().request(); messagingService.get().getUpdateBuffer().request();
} }
} }
@ -203,9 +203,9 @@ public abstract class SubCommand<T> extends Command<T, Void> {
} }
if (!sender.isImport()) { if (!sender.isImport()) {
InternalMessagingService messagingService = plugin.getMessagingService(); Optional<ExtendedMessagingService> messagingService = plugin.getMessagingService();
if (!(messagingService instanceof NoopMessagingService) && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) { if (messagingService.isPresent() && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) {
messagingService.getUpdateBuffer().request(); messagingService.get().getUpdateBuffer().request();
} }
} }
@ -224,9 +224,9 @@ public abstract class SubCommand<T> extends Command<T, Void> {
} }
if (!sender.isImport()) { if (!sender.isImport()) {
InternalMessagingService messagingService = plugin.getMessagingService(); Optional<ExtendedMessagingService> messagingService = plugin.getMessagingService();
if (!(messagingService instanceof NoopMessagingService) && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) { if (messagingService.isPresent() && plugin.getConfiguration().get(ConfigKeys.AUTO_PUSH_UPDATES)) {
messagingService.getUpdateBuffer().request(); messagingService.get().getUpdateBuffer().request();
} }
} }

View File

@ -60,8 +60,8 @@ public class MetaAddChatMeta extends SharedSubCommand {
super( super(
type == ChatMetaType.PREFIX ? CommandSpec.META_ADDPREFIX.spec(locale) : CommandSpec.META_ADDSUFFIX.spec(locale), type == ChatMetaType.PREFIX ? CommandSpec.META_ADDPREFIX.spec(locale) : CommandSpec.META_ADDSUFFIX.spec(locale),
"add" + type.name().toLowerCase(), "add" + type.name().toLowerCase(),
type == ChatMetaType.PREFIX ? CommandPermission.USER_META_ADDPREFIX : CommandPermission.USER_META_ADDSUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.USER_META_ADD_PREFIX : CommandPermission.USER_META_ADD_SUFFIX,
type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_ADDPREFIX : CommandPermission.GROUP_META_ADDSUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_ADD_PREFIX : CommandPermission.GROUP_META_ADD_SUFFIX,
Predicates.inRange(0, 1) Predicates.inRange(0, 1)
); );
this.type = type; this.type = type;

View File

@ -65,8 +65,8 @@ public class MetaAddTempChatMeta extends SharedSubCommand {
super( super(
type == ChatMetaType.PREFIX ? CommandSpec.META_ADDTEMP_PREFIX.spec(locale) : CommandSpec.META_ADDTEMP_SUFFIX.spec(locale), type == ChatMetaType.PREFIX ? CommandSpec.META_ADDTEMP_PREFIX.spec(locale) : CommandSpec.META_ADDTEMP_SUFFIX.spec(locale),
"addtemp" + type.name().toLowerCase(), "addtemp" + type.name().toLowerCase(),
type == ChatMetaType.PREFIX ? CommandPermission.USER_META_ADDTEMP_PREFIX : CommandPermission.USER_META_ADDTEMP_SUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.USER_META_ADD_TEMP_PREFIX : CommandPermission.USER_META_ADD_TEMP_SUFFIX,
type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_ADDTEMP_PREFIX : CommandPermission.GROUP_META_ADDTEMP_SUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_ADD_TEMP_PREFIX : CommandPermission.GROUP_META_ADD_TEMP_SUFFIX,
Predicates.inRange(0, 2) Predicates.inRange(0, 2)
); );
this.type = type; this.type = type;

View File

@ -60,8 +60,8 @@ public class MetaRemoveChatMeta extends SharedSubCommand {
super( super(
type == ChatMetaType.PREFIX ? CommandSpec.META_REMOVEPREFIX.spec(locale) : CommandSpec.META_REMOVESUFFIX.spec(locale), type == ChatMetaType.PREFIX ? CommandSpec.META_REMOVEPREFIX.spec(locale) : CommandSpec.META_REMOVESUFFIX.spec(locale),
"remove" + type.name().toLowerCase(), "remove" + type.name().toLowerCase(),
type == ChatMetaType.PREFIX ? CommandPermission.USER_META_REMOVEPREFIX : CommandPermission.USER_META_REMOVESUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.USER_META_REMOVE_PREFIX : CommandPermission.USER_META_REMOVE_SUFFIX,
type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_REMOVEPREFIX : CommandPermission.GROUP_META_REMOVESUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_REMOVE_PREFIX : CommandPermission.GROUP_META_REMOVE_SUFFIX,
Predicates.is(0) Predicates.is(0)
); );
this.type = type; this.type = type;

View File

@ -60,8 +60,8 @@ public class MetaRemoveTempChatMeta extends SharedSubCommand {
super( super(
type == ChatMetaType.PREFIX ? CommandSpec.META_REMOVETEMP_PREFIX.spec(locale) : CommandSpec.META_REMOVETEMP_SUFFIX.spec(locale), type == ChatMetaType.PREFIX ? CommandSpec.META_REMOVETEMP_PREFIX.spec(locale) : CommandSpec.META_REMOVETEMP_SUFFIX.spec(locale),
"removetemp" + type.name().toLowerCase(), "removetemp" + type.name().toLowerCase(),
type == ChatMetaType.PREFIX ? CommandPermission.USER_META_REMOVETEMP_PREFIX : CommandPermission.USER_META_REMOVETEMP_SUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.USER_META_REMOVE_TEMP_PREFIX : CommandPermission.USER_META_REMOVE_TEMP_SUFFIX,
type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_REMOVETEMP_PREFIX : CommandPermission.GROUP_META_REMOVETEMP_SUFFIX, type == ChatMetaType.PREFIX ? CommandPermission.GROUP_META_REMOVE_TEMP_PREFIX : CommandPermission.GROUP_META_REMOVE_TEMP_SUFFIX,
Predicates.is(0) Predicates.is(0)
); );
this.type = type; this.type = type;

View File

@ -57,7 +57,7 @@ import java.util.stream.Collectors;
public class MetaSetTemp extends SharedSubCommand { public class MetaSetTemp extends SharedSubCommand {
public MetaSetTemp(LocaleManager locale) { public MetaSetTemp(LocaleManager locale) {
super(CommandSpec.META_SETTEMP.spec(locale), "settemp", CommandPermission.USER_META_SETTEMP, CommandPermission.GROUP_META_SETTEMP, Predicates.inRange(0, 2)); super(CommandSpec.META_SETTEMP.spec(locale), "settemp", CommandPermission.USER_META_SET_TEMP, CommandPermission.GROUP_META_SET_TEMP, Predicates.inRange(0, 2));
} }
@Override @Override

View File

@ -47,7 +47,7 @@ import java.util.stream.Collectors;
public class MetaUnsetTemp extends SharedSubCommand { public class MetaUnsetTemp extends SharedSubCommand {
public MetaUnsetTemp(LocaleManager locale) { public MetaUnsetTemp(LocaleManager locale) {
super(CommandSpec.META_UNSETTEMP.spec(locale), "unsettemp", CommandPermission.USER_META_UNSETTEMP, CommandPermission.GROUP_META_UNSETTEMP, Predicates.is(0)); super(CommandSpec.META_UNSETTEMP.spec(locale), "unsettemp", CommandPermission.USER_META_UNSET_TEMP, CommandPermission.GROUP_META_UNSET_TEMP, Predicates.is(0));
} }
@Override @Override

View File

@ -46,7 +46,7 @@ import java.util.stream.Collectors;
public class HolderShowTracks<T extends PermissionHolder> extends SubCommand<T> { public class HolderShowTracks<T extends PermissionHolder> extends SubCommand<T> {
public HolderShowTracks(LocaleManager locale, boolean user) { public HolderShowTracks(LocaleManager locale, boolean user) {
super(CommandSpec.HOLDER_SHOWTRACKS.spec(locale), "showtracks", user ? CommandPermission.USER_SHOWTRACKS : CommandPermission.GROUP_SHOWTRACKS, Predicates.alwaysFalse()); super(CommandSpec.HOLDER_SHOWTRACKS.spec(locale), "showtracks", user ? CommandPermission.USER_SHOW_TRACKS : CommandPermission.GROUP_SHOW_TRACKS, Predicates.alwaysFalse());
} }
@Override @Override

View File

@ -57,7 +57,7 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup
public class ParentAddTemp extends SharedSubCommand { public class ParentAddTemp extends SharedSubCommand {
public ParentAddTemp(LocaleManager locale) { public ParentAddTemp(LocaleManager locale) {
super(CommandSpec.PARENT_ADD_TEMP.spec(locale), "addtemp", CommandPermission.USER_PARENT_ADDTEMP, CommandPermission.GROUP_PARENT_ADDTEMP, Predicates.inRange(0, 1)); super(CommandSpec.PARENT_ADD_TEMP.spec(locale), "addtemp", CommandPermission.USER_PARENT_ADD_TEMP, CommandPermission.GROUP_PARENT_ADD_TEMP, Predicates.inRange(0, 1));
} }
@Override @Override

View File

@ -51,7 +51,7 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup
public class ParentRemoveTemp extends SharedSubCommand { public class ParentRemoveTemp extends SharedSubCommand {
public ParentRemoveTemp(LocaleManager locale) { public ParentRemoveTemp(LocaleManager locale) {
super(CommandSpec.PARENT_REMOVE_TEMP.spec(locale), "removetemp", CommandPermission.USER_PARENT_REMOVETEMP, CommandPermission.GROUP_PARENT_REMOVETEMP, Predicates.is(0)); super(CommandSpec.PARENT_REMOVE_TEMP.spec(locale), "removetemp", CommandPermission.USER_PARENT_REMOVE_TEMP, CommandPermission.GROUP_PARENT_REMOVE_TEMP, Predicates.is(0));
} }
@Override @Override

View File

@ -57,7 +57,7 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi
public class PermissionSetTemp extends SharedSubCommand { public class PermissionSetTemp extends SharedSubCommand {
public PermissionSetTemp(LocaleManager locale) { public PermissionSetTemp(LocaleManager locale) {
super(CommandSpec.PERMISSION_SETTEMP.spec(locale), "settemp", CommandPermission.USER_PERM_SETTEMP, CommandPermission.GROUP_PERM_SETTEMP, Predicates.inRange(0, 2)); super(CommandSpec.PERMISSION_SETTEMP.spec(locale), "settemp", CommandPermission.USER_PERM_SET_TEMP, CommandPermission.GROUP_PERM_SET_TEMP, Predicates.inRange(0, 2));
} }
@Override @Override

View File

@ -51,7 +51,7 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi
public class PermissionUnsetTemp extends SharedSubCommand { public class PermissionUnsetTemp extends SharedSubCommand {
public PermissionUnsetTemp(LocaleManager locale) { public PermissionUnsetTemp(LocaleManager locale) {
super(CommandSpec.PERMISSION_UNSETTEMP.spec(locale), "unsettemp", CommandPermission.USER_PERM_UNSETTEMP, CommandPermission.GROUP_PERM_UNSETTEMP, Predicates.is(0)); super(CommandSpec.PERMISSION_UNSETTEMP.spec(locale), "unsettemp", CommandPermission.USER_PERM_UNSET_TEMP, CommandPermission.GROUP_PERM_UNSET_TEMP, Predicates.is(0));
} }
@Override @Override

View File

@ -67,7 +67,7 @@ import java.util.stream.Collectors;
public class GroupListMembers extends SubCommand<Group> { public class GroupListMembers extends SubCommand<Group> {
public GroupListMembers(LocaleManager locale) { public GroupListMembers(LocaleManager locale) {
super(CommandSpec.GROUP_LISTMEMBERS.spec(locale), "listmembers", CommandPermission.GROUP_LISTMEMBERS, Predicates.notInRange(0, 1)); super(CommandSpec.GROUP_LISTMEMBERS.spec(locale), "listmembers", CommandPermission.GROUP_LIST_MEMBERS, Predicates.notInRange(0, 1));
} }
@Override @Override

View File

@ -44,7 +44,7 @@ import java.util.List;
public class GroupSetWeight extends SubCommand<Group> { public class GroupSetWeight extends SubCommand<Group> {
public GroupSetWeight(LocaleManager locale) { public GroupSetWeight(LocaleManager locale) {
super(CommandSpec.GROUP_SETWEIGHT.spec(locale), "setweight", CommandPermission.GROUP_SETWEIGHT, Predicates.not(1)); super(CommandSpec.GROUP_SETWEIGHT.spec(locale), "setweight", CommandPermission.GROUP_SET_WEIGHT, Predicates.not(1));
} }
@Override @Override

View File

@ -76,11 +76,11 @@ public class CheckCommand extends SingleCommand {
@Override @Override
public List<String> tabComplete(LuckPermsPlugin plugin, Sender sender, List<String> args) { public List<String> tabComplete(LuckPermsPlugin plugin, Sender sender, List<String> args) {
if (args.isEmpty()) { if (args.isEmpty()) {
return plugin.getPlayerList(); return plugin.getPlayerList().collect(Collectors.toList());
} }
if (args.size() == 1) { if (args.size() == 1) {
return plugin.getPlayerList().stream().filter(s -> s.toLowerCase().startsWith(args.get(0).toLowerCase())).collect(Collectors.toList()); return plugin.getPlayerList().filter(s -> s.toLowerCase().startsWith(args.get(0).toLowerCase())).collect(Collectors.toList());
} }
args.remove(0); args.remove(0);

View File

@ -86,7 +86,7 @@ public class ExportCommand extends SingleCommand {
Exporter exporter = new Exporter(plugin, sender, path); Exporter exporter = new Exporter(plugin, sender, path);
// Run the exporter in its own thread. // Run the exporter in its own thread.
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
try { try {
exporter.run(); exporter.run();
} finally { } finally {

View File

@ -89,7 +89,7 @@ public class ImportCommand extends SingleCommand {
Importer importer = new Importer(plugin.getCommandManager(), sender, commands); Importer importer = new Importer(plugin.getCommandManager(), sender, commands);
// Run the importer in its own thread. // Run the importer in its own thread.
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
try { try {
importer.run(); importer.run();
} finally { } finally {

View File

@ -35,7 +35,7 @@ import me.lucko.luckperms.common.constants.CommandPermission;
import me.lucko.luckperms.common.locale.CommandSpec; import me.lucko.luckperms.common.locale.CommandSpec;
import me.lucko.luckperms.common.locale.LocaleManager; import me.lucko.luckperms.common.locale.LocaleManager;
import me.lucko.luckperms.common.locale.Message; import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.NoopMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
@ -69,7 +69,7 @@ public class InfoCommand extends SingleCommand {
} }
Message.INFO_MIDDLE.send(sender, Message.INFO_MIDDLE.send(sender,
plugin.getMessagingService() instanceof NoopMessagingService ? "None" : plugin.getMessagingService().getName(), plugin.getMessagingService().map(ExtendedMessagingService::getName).orElse("None"),
c.get(ConfigKeys.SERVER), c.get(ConfigKeys.SERVER),
plugin.getPlayerCount(), plugin.getPlayerCount(),
plugin.getUniqueConnections().size(), plugin.getUniqueConnections().size(),

View File

@ -32,12 +32,12 @@ import me.lucko.luckperms.common.constants.CommandPermission;
import me.lucko.luckperms.common.locale.CommandSpec; import me.lucko.luckperms.common.locale.CommandSpec;
import me.lucko.luckperms.common.locale.LocaleManager; import me.lucko.luckperms.common.locale.LocaleManager;
import me.lucko.luckperms.common.locale.Message; import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.NoopMessagingService;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import java.util.List; import java.util.List;
import java.util.Optional;
public class NetworkSyncCommand extends SingleCommand { public class NetworkSyncCommand extends SingleCommand {
public NetworkSyncCommand(LocaleManager locale) { public NetworkSyncCommand(LocaleManager locale) {
@ -50,16 +50,15 @@ public class NetworkSyncCommand extends SingleCommand {
plugin.getUpdateTaskBuffer().request().join(); plugin.getUpdateTaskBuffer().request().join();
Message.UPDATE_TASK_COMPLETE_NETWORK.send(sender); Message.UPDATE_TASK_COMPLETE_NETWORK.send(sender);
InternalMessagingService messagingService = plugin.getMessagingService(); Optional<ExtendedMessagingService> messagingService = plugin.getMessagingService();
if (!messagingService.isPresent()) {
if (messagingService instanceof NoopMessagingService) {
Message.UPDATE_TASK_PUSH_FAILURE_NOT_SETUP.send(sender); Message.UPDATE_TASK_PUSH_FAILURE_NOT_SETUP.send(sender);
return CommandResult.FAILURE; return CommandResult.FAILURE;
} }
try { try {
messagingService.pushUpdate(); messagingService.get().pushUpdate();
Message.UPDATE_TASK_PUSH_SUCCESS.send(sender, messagingService.getName()); Message.UPDATE_TASK_PUSH_SUCCESS.send(sender, messagingService.get().getName());
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -52,6 +52,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
public class UserMainCommand extends MainCommand<User, UserIdentifier> { public class UserMainCommand extends MainCommand<User, UserIdentifier> {
@ -143,6 +144,6 @@ public class UserMainCommand extends MainCommand<User, UserIdentifier> {
@Override @Override
protected List<String> getTargets(LuckPermsPlugin plugin) { protected List<String> getTargets(LuckPermsPlugin plugin) {
return plugin.getPlayerList(); return plugin.getPlayerList().collect(Collectors.toList());
} }
} }

View File

@ -25,13 +25,17 @@
package me.lucko.luckperms.common.config; package me.lucko.luckperms.common.config;
import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
import me.lucko.luckperms.common.api.delegates.LPConfigurationDelegate; import me.lucko.luckperms.common.api.delegates.LPConfigurationDelegate;
import me.lucko.luckperms.common.config.keys.EnduringKey; import me.lucko.luckperms.common.config.keys.EnduringKey;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@ -40,16 +44,22 @@ import java.util.stream.Collectors;
/** /**
* An abstract implementation of {@link LuckPermsConfiguration}, backed by a cache. * An abstract implementation of {@link LuckPermsConfiguration}, backed by a cache.
*/ */
public abstract class AbstractConfiguration implements LuckPermsConfiguration { @Getter
@RequiredArgsConstructor
public class AbstractConfiguration implements LuckPermsConfiguration, CacheLoader<ConfigKey<?>, Optional<Object>> {
// the loading cache for config keys --> their value // the loading cache for config keys --> their value
// the value is wrapped in an optional as null values don't get cached. // the value is wrapped in an optional as null values don't get cached.
private final LoadingCache<ConfigKey<?>, Optional<Object>> cache = Caffeine.newBuilder().build(this::loadKeyValue); @Getter(AccessLevel.NONE)
private final LoadingCache<ConfigKey<?>, Optional<Object>> cache = Caffeine.newBuilder().build(this);
@Getter // the plugin instance
private final LuckPermsPlugin plugin;
// the adapter used to read values
private final ConfigurationAdapter adapter;
// the api delegate
private final LPConfigurationDelegate delegate = new LPConfigurationDelegate(this); private final LPConfigurationDelegate delegate = new LPConfigurationDelegate(this);
// the contextsfile handler
@Getter
private final ContextsFile contextsFile = new ContextsFile(this); private final ContextsFile contextsFile = new ContextsFile(this);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -68,6 +78,12 @@ public abstract class AbstractConfiguration implements LuckPermsConfiguration {
contextsFile.load(); contextsFile.load();
} }
@Override
public void init() {
adapter.init();
loadAll();
}
@Override @Override
public void reload() { public void reload() {
init(); init();
@ -79,7 +95,8 @@ public abstract class AbstractConfiguration implements LuckPermsConfiguration {
getPlugin().getApiProvider().getEventFactory().handleConfigReload(); getPlugin().getApiProvider().getEventFactory().handleConfigReload();
} }
private Optional<Object> loadKeyValue(ConfigKey<?> key) { @Override
return Optional.ofNullable(key.get(this)); public Optional<Object> load(ConfigKey<?> key) {
return Optional.ofNullable(key.get(adapter));
} }
} }

View File

@ -38,9 +38,9 @@ public interface ConfigKey<T> {
* <p>The {@link LuckPermsConfiguration#get(ConfigKey)} method should be used to * <p>The {@link LuckPermsConfiguration#get(ConfigKey)} method should be used to
* retrieve the value, as opposed to calling this directly.</p> * retrieve the value, as opposed to calling this directly.</p>
* *
* @param config the config instance * @param adapter the config adapter instance
* @return the value mapped to this key * @return the value mapped to this key
*/ */
T get(LuckPermsConfiguration config); T get(ConfigurationAdapter adapter);
} }

View File

@ -23,35 +23,31 @@
* SOFTWARE. * SOFTWARE.
*/ */
package me.lucko.luckperms.common.messaging; package me.lucko.luckperms.common.config;
import me.lucko.luckperms.api.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.buffers.BufferedRequest;
public class NoopMessagingService implements InternalMessagingService { import java.util.List;
import java.util.Map;
@Override public interface ConfigurationAdapter {
public String getName() {
return "No op";
}
@Override LuckPermsPlugin getPlugin();
public void close() {
} void init();
@Override boolean contains(String path);
public BufferedRequest<Void> getUpdateBuffer() {
return null;
}
@Override String getString(String path, String def);
public void pushLog(LogEntry logEntry) {
} int getInt(String path, int def);
@Override boolean getBoolean(String path, boolean def);
public void pushUpdate() {
List<String> getList(String path, List<String> def);
List<String> getObjectList(String path, List<String> def);
Map<String, String> getMap(String path, Map<String, String> def);
}
} }

View File

@ -28,9 +28,6 @@ package me.lucko.luckperms.common.config;
import me.lucko.luckperms.common.api.delegates.LPConfigurationDelegate; import me.lucko.luckperms.common.api.delegates.LPConfigurationDelegate;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import java.util.List;
import java.util.Map;
/** /**
* The master configuration used by LuckPerms. * The master configuration used by LuckPerms.
*/ */
@ -81,22 +78,4 @@ public interface LuckPermsConfiguration {
*/ */
<T> T get(ConfigKey<T> key); <T> T get(ConfigKey<T> key);
/* methods used by config keys to load their values */
boolean contains(String path);
String getString(String path, String def);
int getInt(String path, int def);
boolean getBoolean(String path, boolean def);
List<String> getList(String path, List<String> def);
List<String> getObjectList(String path, List<String> def);
Map<String, String> getMap(String path, Map<String, String> def);
} }

View File

@ -28,16 +28,16 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
import java.util.function.Function; import java.util.function.Function;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class AbstractKey<T> implements ConfigKey<T> { public class AbstractKey<T> implements ConfigKey<T> {
private final Function<LuckPermsConfiguration, T> function; private final Function<ConfigurationAdapter, T> function;
@Override @Override
public T get(LuckPermsConfiguration config) { public T get(ConfigurationAdapter adapter) {
return function.apply(config); return function.apply(adapter);
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class BooleanKey implements ConfigKey<Boolean> { public class BooleanKey implements ConfigKey<Boolean> {
@ -36,7 +36,7 @@ public class BooleanKey implements ConfigKey<Boolean> {
private final boolean def; private final boolean def;
@Override @Override
public Boolean get(LuckPermsConfiguration config) { public Boolean get(ConfigurationAdapter adapter) {
return config.getBoolean(path, def); return adapter.getBoolean(path, def);
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class IntegerKey implements ConfigKey<Integer> { public class IntegerKey implements ConfigKey<Integer> {
@ -36,7 +36,7 @@ public class IntegerKey implements ConfigKey<Integer> {
private final int def; private final int def;
@Override @Override
public Integer get(LuckPermsConfiguration config) { public Integer get(ConfigurationAdapter adapter) {
return config.getInt(path, def); return adapter.getInt(path, def);
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class LowercaseStringKey implements ConfigKey<String> { public class LowercaseStringKey implements ConfigKey<String> {
@ -36,7 +36,7 @@ public class LowercaseStringKey implements ConfigKey<String> {
private final String def; private final String def;
@Override @Override
public String get(LuckPermsConfiguration config) { public String get(ConfigurationAdapter adapter) {
return config.getString(path, def).toLowerCase(); return adapter.getString(path, def).toLowerCase();
} }
} }

View File

@ -30,7 +30,7 @@ import lombok.AllArgsConstructor;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
import java.util.Map; import java.util.Map;
@ -39,7 +39,7 @@ public class MapKey implements ConfigKey<Map<String, String>> {
private final String path; private final String path;
@Override @Override
public Map<String, String> get(LuckPermsConfiguration config) { public Map<String, String> get(ConfigurationAdapter adapter) {
return ImmutableMap.copyOf(config.getMap(path, ImmutableMap.of())); return ImmutableMap.copyOf(adapter.getMap(path, ImmutableMap.of()));
} }
} }

View File

@ -28,14 +28,14 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class StaticKey<T> implements ConfigKey<T> { public class StaticKey<T> implements ConfigKey<T> {
private final T val; private final T val;
@Override @Override
public T get(LuckPermsConfiguration config) { public T get(ConfigurationAdapter adapter) {
return val; return val;
} }
} }

View File

@ -28,7 +28,7 @@ package me.lucko.luckperms.common.config.keys;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import me.lucko.luckperms.common.config.ConfigKey; import me.lucko.luckperms.common.config.ConfigKey;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class StringKey implements ConfigKey<String> { public class StringKey implements ConfigKey<String> {
@ -36,7 +36,7 @@ public class StringKey implements ConfigKey<String> {
private final String def; private final String def;
@Override @Override
public String get(LuckPermsConfiguration config) { public String get(ConfigurationAdapter adapter) {
return config.getString(path, def); return adapter.getString(path, def);
} }
} }

View File

@ -67,8 +67,8 @@ public enum CommandPermission {
USER_PERM_INFO("permission.info", USER), USER_PERM_INFO("permission.info", USER),
USER_PERM_SET("permission.set", USER), USER_PERM_SET("permission.set", USER),
USER_PERM_UNSET("permission.unset", USER), USER_PERM_UNSET("permission.unset", USER),
USER_PERM_SETTEMP("permission.settemp", USER), USER_PERM_SET_TEMP("permission.settemp", USER),
USER_PERM_UNSETTEMP("permission.unsettemp", USER), USER_PERM_UNSET_TEMP("permission.unsettemp", USER),
USER_PERM_CHECK("permission.check", USER), USER_PERM_CHECK("permission.check", USER),
USER_PERM_CHECK_INHERITS("permission.checkinherits", USER), USER_PERM_CHECK_INHERITS("permission.checkinherits", USER),
USER_PARENT_INFO("parent.info", USER), USER_PARENT_INFO("parent.info", USER),
@ -76,27 +76,27 @@ public enum CommandPermission {
USER_PARENT_SET_TRACK("parent.settrack", USER), USER_PARENT_SET_TRACK("parent.settrack", USER),
USER_PARENT_ADD("parent.add", USER), USER_PARENT_ADD("parent.add", USER),
USER_PARENT_REMOVE("parent.remove", USER), USER_PARENT_REMOVE("parent.remove", USER),
USER_PARENT_ADDTEMP("parent.addtemp", USER), USER_PARENT_ADD_TEMP("parent.addtemp", USER),
USER_PARENT_REMOVETEMP("parent.removetemp", USER), USER_PARENT_REMOVE_TEMP("parent.removetemp", USER),
USER_PARENT_CLEAR("parent.clear", USER), USER_PARENT_CLEAR("parent.clear", USER),
USER_PARENT_CLEAR_TRACK("parent.cleartrack", USER), USER_PARENT_CLEAR_TRACK("parent.cleartrack", USER),
USER_META_INFO("meta.info", USER), USER_META_INFO("meta.info", USER),
USER_META_SET("meta.set", USER), USER_META_SET("meta.set", USER),
USER_META_UNSET("meta.unset", USER), USER_META_UNSET("meta.unset", USER),
USER_META_SETTEMP("meta.settemp", USER), USER_META_SET_TEMP("meta.settemp", USER),
USER_META_UNSETTEMP("meta.unsettemp", USER), USER_META_UNSET_TEMP("meta.unsettemp", USER),
USER_META_ADDPREFIX("meta.addprefix", USER), USER_META_ADD_PREFIX("meta.addprefix", USER),
USER_META_ADDSUFFIX("meta.addsuffix", USER), USER_META_ADD_SUFFIX("meta.addsuffix", USER),
USER_META_REMOVEPREFIX("meta.removeprefix", USER), USER_META_REMOVE_PREFIX("meta.removeprefix", USER),
USER_META_REMOVESUFFIX("meta.removesuffix", USER), USER_META_REMOVE_SUFFIX("meta.removesuffix", USER),
USER_META_ADDTEMP_PREFIX("meta.addtempprefix", USER), USER_META_ADD_TEMP_PREFIX("meta.addtempprefix", USER),
USER_META_ADDTEMP_SUFFIX("meta.addtempsuffix", USER), USER_META_ADD_TEMP_SUFFIX("meta.addtempsuffix", USER),
USER_META_REMOVETEMP_PREFIX("meta.removetempprefix", USER), USER_META_REMOVE_TEMP_PREFIX("meta.removetempprefix", USER),
USER_META_REMOVETEMP_SUFFIX("meta.removetempsuffix", USER), USER_META_REMOVE_TEMP_SUFFIX("meta.removetempsuffix", USER),
USER_META_CLEAR("meta.clear", USER), USER_META_CLEAR("meta.clear", USER),
USER_EDITOR("editor", USER), USER_EDITOR("editor", USER),
USER_SWITCHPRIMARYGROUP("switchprimarygroup", USER), USER_SWITCHPRIMARYGROUP("switchprimarygroup", USER),
USER_SHOWTRACKS("showtracks", USER), USER_SHOW_TRACKS("showtracks", USER),
USER_PROMOTE("promote", USER), USER_PROMOTE("promote", USER),
USER_DEMOTE("demote", USER), USER_DEMOTE("demote", USER),
USER_CLEAR("clear", USER), USER_CLEAR("clear", USER),
@ -105,8 +105,8 @@ public enum CommandPermission {
GROUP_PERM_INFO("permission.info", GROUP), GROUP_PERM_INFO("permission.info", GROUP),
GROUP_PERM_SET("permission.set", GROUP), GROUP_PERM_SET("permission.set", GROUP),
GROUP_PERM_UNSET("permission.unset", GROUP), GROUP_PERM_UNSET("permission.unset", GROUP),
GROUP_PERM_SETTEMP("permission.settemp", GROUP), GROUP_PERM_SET_TEMP("permission.settemp", GROUP),
GROUP_PERM_UNSETTEMP("permission.unsettemp", GROUP), GROUP_PERM_UNSET_TEMP("permission.unsettemp", GROUP),
GROUP_PERM_CHECK("permission.check", GROUP), GROUP_PERM_CHECK("permission.check", GROUP),
GROUP_PERM_CHECK_INHERITS("permission.checkinherits", GROUP), GROUP_PERM_CHECK_INHERITS("permission.checkinherits", GROUP),
GROUP_PARENT_INFO("parent.info", GROUP), GROUP_PARENT_INFO("parent.info", GROUP),
@ -114,28 +114,28 @@ public enum CommandPermission {
GROUP_PARENT_SET_TRACK("parent.settrack", GROUP), GROUP_PARENT_SET_TRACK("parent.settrack", GROUP),
GROUP_PARENT_ADD("parent.add", GROUP), GROUP_PARENT_ADD("parent.add", GROUP),
GROUP_PARENT_REMOVE("parent.remove", GROUP), GROUP_PARENT_REMOVE("parent.remove", GROUP),
GROUP_PARENT_ADDTEMP("parent.addtemp", GROUP), GROUP_PARENT_ADD_TEMP("parent.addtemp", GROUP),
GROUP_PARENT_REMOVETEMP("parent.removetemp", GROUP), GROUP_PARENT_REMOVE_TEMP("parent.removetemp", GROUP),
GROUP_PARENT_CLEAR("parent.clear", GROUP), GROUP_PARENT_CLEAR("parent.clear", GROUP),
GROUP_PARENT_CLEAR_TRACK("parent.cleartrack", GROUP), GROUP_PARENT_CLEAR_TRACK("parent.cleartrack", GROUP),
GROUP_META_INFO("meta.info", GROUP), GROUP_META_INFO("meta.info", GROUP),
GROUP_META_SET("meta.set", GROUP), GROUP_META_SET("meta.set", GROUP),
GROUP_META_UNSET("meta.unset", GROUP), GROUP_META_UNSET("meta.unset", GROUP),
GROUP_META_SETTEMP("meta.settemp", GROUP), GROUP_META_SET_TEMP("meta.settemp", GROUP),
GROUP_META_UNSETTEMP("meta.unsettemp", GROUP), GROUP_META_UNSET_TEMP("meta.unsettemp", GROUP),
GROUP_META_ADDPREFIX("meta.addprefix", GROUP), GROUP_META_ADD_PREFIX("meta.addprefix", GROUP),
GROUP_META_ADDSUFFIX("meta.addsuffix", GROUP), GROUP_META_ADD_SUFFIX("meta.addsuffix", GROUP),
GROUP_META_REMOVEPREFIX("meta.removeprefix", GROUP), GROUP_META_REMOVE_PREFIX("meta.removeprefix", GROUP),
GROUP_META_REMOVESUFFIX("meta.removesuffix", GROUP), GROUP_META_REMOVE_SUFFIX("meta.removesuffix", GROUP),
GROUP_META_ADDTEMP_PREFIX("meta.addtempprefix", GROUP), GROUP_META_ADD_TEMP_PREFIX("meta.addtempprefix", GROUP),
GROUP_META_ADDTEMP_SUFFIX("meta.addtempsuffix", GROUP), GROUP_META_ADD_TEMP_SUFFIX("meta.addtempsuffix", GROUP),
GROUP_META_REMOVETEMP_PREFIX("meta.removetempprefix", GROUP), GROUP_META_REMOVE_TEMP_PREFIX("meta.removetempprefix", GROUP),
GROUP_META_REMOVETEMP_SUFFIX("meta.removetempsuffix", GROUP), GROUP_META_REMOVE_TEMP_SUFFIX("meta.removetempsuffix", GROUP),
GROUP_META_CLEAR("meta.clear", GROUP), GROUP_META_CLEAR("meta.clear", GROUP),
GROUP_EDITOR("editor", GROUP), GROUP_EDITOR("editor", GROUP),
GROUP_LISTMEMBERS("listmembers", GROUP), GROUP_LIST_MEMBERS("listmembers", GROUP),
GROUP_SHOWTRACKS("showtracks", GROUP), GROUP_SHOW_TRACKS("showtracks", GROUP),
GROUP_SETWEIGHT("setweight", GROUP), GROUP_SET_WEIGHT("setweight", GROUP),
GROUP_SET_DISPLAY_NAME("setdisplayname", GROUP), GROUP_SET_DISPLAY_NAME("setdisplayname", GROUP),
GROUP_CLEAR("clear", GROUP), GROUP_CLEAR("clear", GROUP),
GROUP_RENAME("rename", GROUP), GROUP_RENAME("rename", GROUP),

View File

@ -107,6 +107,6 @@ public class LuckPermsEventBus implements EventBus {
if (event instanceof Cancellable) { if (event instanceof Cancellable) {
throw new IllegalArgumentException("cannot call Cancellable event async"); throw new IllegalArgumentException("cannot call Cancellable event async");
} }
plugin.doAsync(() -> fireEvent(event)); plugin.getScheduler().doAsync(() -> fireEvent(event));
} }
} }

View File

@ -113,12 +113,10 @@ public class GenericUserManager extends AbstractManager<UserIdentifier, User> im
@Override @Override
public CompletableFuture<Void> updateAllUsers() { public CompletableFuture<Void> updateAllUsers() {
return CompletableFuture.supplyAsync(plugin::getOnlinePlayers, plugin.getScheduler().sync()) return CompletableFuture.supplyAsync(plugin::getOnlinePlayers, plugin.getScheduler().sync())
.thenAcceptAsync(players -> { .thenAcceptAsync(players -> players.forEach(uuid -> {
for (UUID uuid : players) { UUID internal = plugin.getUuidCache().getUUID(uuid);
UUID internal = plugin.getUuidCache().getUUID(uuid); plugin.getStorage().loadUser(internal, "null").join();
plugin.getStorage().loadUser(internal, "null").join(); }), plugin.getScheduler().async());
}
}, plugin.getScheduler().async());
} }
public static boolean giveDefaultIfNeeded(User user, boolean save, LuckPermsPlugin plugin) { public static boolean giveDefaultIfNeeded(User user, boolean save, LuckPermsPlugin plugin) {

View File

@ -46,7 +46,7 @@ import java.util.function.Consumer;
/** /**
* An abstract implementation of {@link me.lucko.luckperms.api.MessagingService}. * An abstract implementation of {@link me.lucko.luckperms.api.MessagingService}.
*/ */
public abstract class AbstractMessagingService implements InternalMessagingService { public abstract class AbstractMessagingService implements ExtendedMessagingService {
protected static final String CHANNEL = "lpuc"; protected static final String CHANNEL = "lpuc";
@Getter @Getter
@ -69,13 +69,9 @@ public abstract class AbstractMessagingService implements InternalMessagingServi
this.updateBuffer = new PushUpdateBuffer(plugin); this.updateBuffer = new PushUpdateBuffer(plugin);
} }
protected abstract void sendMessage(String channel, String message); protected abstract void sendMessage(String message);
protected void onMessage(String channel, String msg, Consumer<String> callback) {
if (!channel.equals(CHANNEL)) {
return;
}
protected void onMessage(String msg, Consumer<String> callback) {
if (msg.startsWith("update:") && msg.length() > "update:".length()) { if (msg.startsWith("update:") && msg.length() > "update:".length()) {
UUID uuid = parseUpdateMessage(msg); UUID uuid = parseUpdateMessage(msg);
if (uuid == null) { if (uuid == null) {
@ -127,7 +123,7 @@ public abstract class AbstractMessagingService implements InternalMessagingServi
@Override @Override
public void pushLog(LogEntry logEntry) { public void pushLog(LogEntry logEntry) {
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
UUID id = generatePingId(); UUID id = generatePingId();
if (plugin.getApiProvider().getEventFactory().handleLogNetworkPublish(!plugin.getConfiguration().get(ConfigKeys.PUSH_LOG_ENTRIES), id, logEntry)) { if (plugin.getApiProvider().getEventFactory().handleLogNetworkPublish(!plugin.getConfiguration().get(ConfigKeys.PUSH_LOG_ENTRIES), id, logEntry)) {
@ -135,17 +131,17 @@ public abstract class AbstractMessagingService implements InternalMessagingServi
} }
plugin.getLog().info("[" + name + " Messaging] Sending log with id: " + id.toString()); plugin.getLog().info("[" + name + " Messaging] Sending log with id: " + id.toString());
sendMessage(CHANNEL, "log:" + gson.toJson(ExtendedLogEntry.serializeWithId(id, logEntry))); sendMessage("log:" + gson.toJson(ExtendedLogEntry.serializeWithId(id, logEntry)));
}); });
} }
@Override @Override
public void pushUpdate() { public void pushUpdate() {
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
UUID id = generatePingId(); UUID id = generatePingId();
plugin.getLog().info("[" + name + " Messaging] Sending ping with id: " + id.toString()); plugin.getLog().info("[" + name + " Messaging] Sending ping with id: " + id.toString());
sendMessage(CHANNEL, "update:" + id.toString()); sendMessage("update:" + id.toString());
}); });
} }
@ -166,7 +162,7 @@ public abstract class AbstractMessagingService implements InternalMessagingServi
private final class PushUpdateBuffer extends BufferedRequest<Void> { private final class PushUpdateBuffer extends BufferedRequest<Void> {
public PushUpdateBuffer(LuckPermsPlugin plugin) { public PushUpdateBuffer(LuckPermsPlugin plugin) {
super(3000L, 200L, plugin::doAsync); super(3000L, 200L, plugin.getScheduler().async());
} }
@Override @Override

View File

@ -29,7 +29,7 @@ import me.lucko.luckperms.api.LogEntry;
import me.lucko.luckperms.api.MessagingService; import me.lucko.luckperms.api.MessagingService;
import me.lucko.luckperms.common.buffers.BufferedRequest; import me.lucko.luckperms.common.buffers.BufferedRequest;
public interface InternalMessagingService extends MessagingService { public interface ExtendedMessagingService extends MessagingService {
/** /**
* Gets the name of this messaging service * Gets the name of this messaging service

View File

@ -38,28 +38,28 @@ public class MessagingFactory<P extends LuckPermsPlugin> {
@Getter(AccessLevel.PROTECTED) @Getter(AccessLevel.PROTECTED)
private final P plugin; private final P plugin;
public final InternalMessagingService getInstance() { public final ExtendedMessagingService getInstance() {
String messagingType = plugin.getConfiguration().get(ConfigKeys.MESSAGING_SERVICE).toLowerCase(); String messagingType = plugin.getConfiguration().get(ConfigKeys.MESSAGING_SERVICE).toLowerCase();
if (messagingType.equals("none") && plugin.getConfiguration().get(ConfigKeys.REDIS_ENABLED)) { if (messagingType.equals("none") && plugin.getConfiguration().get(ConfigKeys.REDIS_ENABLED)) {
messagingType = "redis"; messagingType = "redis";
} }
if (messagingType.equals("none")) { if (messagingType.equals("none")) {
return new NoopMessagingService(); return null;
} }
plugin.getLog().info("Loading messaging service... [" + messagingType.toUpperCase() + "]"); plugin.getLog().info("Loading messaging service... [" + messagingType.toUpperCase() + "]");
InternalMessagingService service = getServiceFor(messagingType); ExtendedMessagingService service = getServiceFor(messagingType);
if (service != null) { if (service != null) {
return service; return service;
} }
plugin.getLog().warn("Messaging service '" + messagingType + "' not recognised."); plugin.getLog().warn("Messaging service '" + messagingType + "' not recognised.");
return new NoopMessagingService(); return null;
} }
protected InternalMessagingService getServiceFor(String messagingType) { protected ExtendedMessagingService getServiceFor(String messagingType) {
if (messagingType.equals("redis")) { if (messagingType.equals("redis")) {
if (plugin.getConfiguration().get(ConfigKeys.REDIS_ENABLED)) { if (plugin.getConfiguration().get(ConfigKeys.REDIS_ENABLED)) {
RedisMessagingService redis = new RedisMessagingService(plugin); RedisMessagingService redis = new RedisMessagingService(plugin);

View File

@ -58,7 +58,7 @@ public class RedisMessagingService extends AbstractMessagingService {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, password); jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, password);
} }
plugin.doAsync(() -> { plugin.getScheduler().doAsync(() -> {
sub = new LPSub(this); sub = new LPSub(this);
try (Jedis jedis = jedisPool.getResource()) { try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(sub, CHANNEL); jedis.subscribe(sub, CHANNEL);
@ -75,7 +75,7 @@ public class RedisMessagingService extends AbstractMessagingService {
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
try (Jedis jedis = jedisPool.getResource()) { try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(CHANNEL, message); jedis.publish(CHANNEL, message);
} catch (Exception e) { } catch (Exception e) {
@ -89,7 +89,10 @@ public class RedisMessagingService extends AbstractMessagingService {
@Override @Override
public void onMessage(String channel, String msg) { public void onMessage(String channel, String msg) {
parent.onMessage(channel, msg, null); if (!channel.equals(CHANNEL)) {
return;
}
parent.onMessage(msg, null);
} }
} }

View File

@ -68,10 +68,10 @@ public class User extends PermissionHolder implements Identifiable<UserIdentifie
* The users data cache instance, if present. * The users data cache instance, if present.
*/ */
@Getter @Getter
private final UserCache userData = new UserCache(this); private final UserCache userData;
@Getter @Getter
private BufferedRequest<Void> refreshBuffer = new UserRefreshBuffer(this); private BufferedRequest<Void> refreshBuffer;
@Getter @Getter
private final UserDelegate delegate = new UserDelegate(this); private final UserDelegate delegate = new UserDelegate(this);
@ -80,16 +80,22 @@ public class User extends PermissionHolder implements Identifiable<UserIdentifie
super(uuid.toString(), plugin); super(uuid.toString(), plugin);
this.uuid = uuid; this.uuid = uuid;
this.refreshBuffer = new UserRefreshBuffer(plugin, this);
this.primaryGroup = plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION).apply(this); this.primaryGroup = plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION).apply(this);
this.userData = new UserCache(this);
getPlugin().getApiProvider().getEventFactory().handleUserCacheLoad(this, userData); getPlugin().getApiProvider().getEventFactory().handleUserCacheLoad(this, userData);
} }
public User(UUID uuid, String name, LuckPermsPlugin plugin) { public User(UUID uuid, String name, LuckPermsPlugin plugin) {
super(uuid.toString(), plugin); super(uuid.toString(), plugin);
this.uuid = uuid; this.uuid = uuid;
setName(name, false); setName(name, false);
this.refreshBuffer = new UserRefreshBuffer(plugin, this);
this.primaryGroup = plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION).apply(this); this.primaryGroup = plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION).apply(this);
this.userData = new UserCache(this);
getPlugin().getApiProvider().getEventFactory().handleUserCacheLoad(this, userData); getPlugin().getApiProvider().getEventFactory().handleUserCacheLoad(this, userData);
} }
@ -207,8 +213,8 @@ public class User extends PermissionHolder implements Identifiable<UserIdentifie
private static final class UserRefreshBuffer extends BufferedRequest<Void> { private static final class UserRefreshBuffer extends BufferedRequest<Void> {
private final User user; private final User user;
private UserRefreshBuffer(User user) { private UserRefreshBuffer(LuckPermsPlugin plugin, User user) {
super(250L, 50L, r -> user.getPlugin().doAsync(r)); super(250L, 50L, plugin.getScheduler().async());
this.user = user; this.user = user;
} }

View File

@ -44,7 +44,7 @@ import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.managers.GroupManager; import me.lucko.luckperms.common.managers.GroupManager;
import me.lucko.luckperms.common.managers.TrackManager; import me.lucko.luckperms.common.managers.TrackManager;
import me.lucko.luckperms.common.managers.UserManager; import me.lucko.luckperms.common.managers.UserManager;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.storage.dao.file.FileWatcher; import me.lucko.luckperms.common.storage.dao.file.FileWatcher;
@ -60,7 +60,7 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer; import java.util.stream.Stream;
/** /**
* Main internal interface for LuckPerms plugins, providing the base for abstraction throughout the project. * Main internal interface for LuckPerms plugins, providing the base for abstraction throughout the project.
@ -109,7 +109,7 @@ public interface LuckPermsPlugin {
* *
* @return the redis messaging service * @return the redis messaging service
*/ */
InternalMessagingService getMessagingService(); Optional<ExtendedMessagingService> getMessagingService();
/** /**
* Gets a wrapped logger instance for the platform. * Gets a wrapped logger instance for the platform.
@ -194,15 +194,14 @@ public interface LuckPermsPlugin {
* *
* @return the scheduler * @return the scheduler
*/ */
LuckPermsScheduler getScheduler(); SchedulerAdapter getScheduler();
default void doAsync(Runnable runnable) { /**
getScheduler().doAsync(runnable); * Gets the file watcher running on the platform
} *
* @return the file watcher
default void doSync(Runnable runnable) { */
getScheduler().doSync(runnable); Optional<FileWatcher> getFileWatcher();
}
/** /**
* Gets a string of the plugin's version * Gets a string of the plugin's version
@ -239,20 +238,6 @@ public interface LuckPermsPlugin {
*/ */
long getStartTime(); long getStartTime();
/**
* Gets the file watcher running on the platform, or null if it's not enabled.
*
* @return the file watcher, or null
*/
FileWatcher getFileWatcher();
default void applyToFileWatcher(Consumer<FileWatcher> consumer) {
FileWatcher fw = getFileWatcher();
if (fw != null) {
consumer.accept(fw);
}
}
/** /**
* Gets the plugins main data storage directory * Gets the plugins main data storage directory
* *
@ -331,14 +316,14 @@ public interface LuckPermsPlugin {
* *
* @return a {@link List} of usernames * @return a {@link List} of usernames
*/ */
List<String> getPlayerList(); Stream<String> getPlayerList();
/** /**
* Gets the UUIDs of the users online on the platform * Gets the UUIDs of the users online on the platform
* *
* @return a {@link Set} of UUIDs * @return a {@link Set} of UUIDs
*/ */
Set<UUID> getOnlinePlayers(); Stream<UUID> getOnlinePlayers();
/** /**
* Checks if a user is online * Checks if a user is online
@ -353,7 +338,7 @@ public interface LuckPermsPlugin {
* *
* @return a {@link List} of senders online on the platform * @return a {@link List} of senders online on the platform
*/ */
List<Sender> getOnlineSenders(); Stream<Sender> getOnlineSenders();
/** /**
* Gets the console. * Gets the console.

View File

@ -30,7 +30,7 @@ import java.util.concurrent.Executor;
/** /**
* A scheduler for running tasks using the systems provided by the platform * A scheduler for running tasks using the systems provided by the platform
*/ */
public interface LuckPermsScheduler { public interface SchedulerAdapter {
/** /**
* Gets an async executor instance * Gets an async executor instance

View File

@ -144,7 +144,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
private void registerFileAction(StorageLocation type, File file) { private void registerFileAction(StorageLocation type, File file) {
plugin.applyToFileWatcher(fileWatcher -> fileWatcher.registerChange(type, file.getName())); plugin.getFileWatcher().ifPresent(fileWatcher -> fileWatcher.registerChange(type, file.getName()));
} }
@Override @Override
@ -241,7 +241,7 @@ public abstract class ConfigurateDao extends AbstractDao {
actionLogFile.createNewFile(); actionLogFile.createNewFile();
// Listen for file changes. // Listen for file changes.
plugin.applyToFileWatcher(watcher -> { plugin.getFileWatcher().ifPresent(watcher -> {
watcher.subscribe("user", usersDirectory.toPath(), s -> { watcher.subscribe("user", usersDirectory.toPath(), s -> {
if (!s.endsWith(fileExtension)) { if (!s.endsWith(fileExtension)) {
return; return;
@ -287,11 +287,10 @@ public abstract class ConfigurateDao extends AbstractDao {
@Override @Override
public boolean logAction(LogEntry entry) { public boolean logAction(LogEntry entry) {
//noinspection deprecation
actionLogger.info(String.format(LOG_FORMAT, actionLogger.info(String.format(LOG_FORMAT,
(entry.getActor().equals(Constants.CONSOLE_UUID) ? "" : entry.getActor() + " "), (entry.getActor().equals(Constants.CONSOLE_UUID) ? "" : entry.getActor() + " "),
entry.getActorName(), entry.getActorName(),
Character.toString(entry.getType()), Character.toString(entry.getEntryType().getCode()),
(entry.getActed() == null ? "" : entry.getActed().toString() + " "), (entry.getActed() == null ? "" : entry.getActed().toString() + " "),
entry.getActedName(), entry.getActedName(),
entry.getAction()) entry.getAction())

View File

@ -161,12 +161,11 @@ public class MongoDao extends AbstractDao {
try { try {
MongoCollection<Document> c = database.getCollection(prefix + "action"); MongoCollection<Document> c = database.getCollection(prefix + "action");
//noinspection deprecation
Document doc = new Document() Document doc = new Document()
.append("timestamp", entry.getTimestamp()) .append("timestamp", entry.getTimestamp())
.append("actor", entry.getActor()) .append("actor", entry.getActor())
.append("actorName", entry.getActorName()) .append("actorName", entry.getActorName())
.append("type", Character.toString(entry.getType())) .append("type", Character.toString(entry.getEntryType().getCode()))
.append("actedName", entry.getActedName()) .append("actedName", entry.getActedName())
.append("action", entry.getAction()); .append("action", entry.getAction());

View File

@ -224,8 +224,7 @@ public class SqlDao extends AbstractDao {
ps.setLong(1, entry.getTimestamp()); ps.setLong(1, entry.getTimestamp());
ps.setString(2, entry.getActor().toString()); ps.setString(2, entry.getActor().toString());
ps.setString(3, entry.getActorName()); ps.setString(3, entry.getActorName());
//noinspection deprecation ps.setString(4, Character.toString(entry.getEntryType().getCode()));
ps.setString(4, Character.toString(entry.getType()));
ps.setString(5, entry.getActed() == null ? "null" : entry.getActed().toString()); ps.setString(5, entry.getActed() == null ? "null" : entry.getActed().toString());
ps.setString(6, entry.getActedName()); ps.setString(6, entry.getActedName());
ps.setString(7, entry.getAction()); ps.setString(7, entry.getAction());

View File

@ -42,6 +42,7 @@ import me.lucko.luckperms.common.caching.handlers.CachedStateManager;
import me.lucko.luckperms.common.calculators.CalculatorFactory; import me.lucko.luckperms.common.calculators.CalculatorFactory;
import me.lucko.luckperms.common.commands.abstraction.Command; import me.lucko.luckperms.common.commands.abstraction.Command;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.config.AbstractConfiguration;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.config.LuckPermsConfiguration; import me.lucko.luckperms.common.config.LuckPermsConfiguration;
import me.lucko.luckperms.common.constants.CommandPermission; import me.lucko.luckperms.common.constants.CommandPermission;
@ -55,10 +56,10 @@ import me.lucko.luckperms.common.locale.SimpleLocaleManager;
import me.lucko.luckperms.common.logging.SenderLogger; import me.lucko.luckperms.common.logging.SenderLogger;
import me.lucko.luckperms.common.managers.GenericTrackManager; import me.lucko.luckperms.common.managers.GenericTrackManager;
import me.lucko.luckperms.common.managers.TrackManager; import me.lucko.luckperms.common.managers.TrackManager;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.plugin.LuckPermsScheduler; import me.lucko.luckperms.common.plugin.SchedulerAdapter;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.storage.StorageFactory; import me.lucko.luckperms.common.storage.StorageFactory;
import me.lucko.luckperms.common.storage.StorageType; import me.lucko.luckperms.common.storage.StorageType;
@ -73,6 +74,8 @@ import me.lucko.luckperms.sponge.calculators.SpongeCalculatorFactory;
import me.lucko.luckperms.sponge.commands.SpongeMainCommand; import me.lucko.luckperms.sponge.commands.SpongeMainCommand;
import me.lucko.luckperms.sponge.contexts.SpongeContextManager; import me.lucko.luckperms.sponge.contexts.SpongeContextManager;
import me.lucko.luckperms.sponge.contexts.WorldCalculator; import me.lucko.luckperms.sponge.contexts.WorldCalculator;
import me.lucko.luckperms.sponge.listeners.SpongeConnectionListener;
import me.lucko.luckperms.sponge.listeners.SpongePlatformListener;
import me.lucko.luckperms.sponge.managers.SpongeGroupManager; import me.lucko.luckperms.sponge.managers.SpongeGroupManager;
import me.lucko.luckperms.sponge.managers.SpongeUserManager; import me.lucko.luckperms.sponge.managers.SpongeUserManager;
import me.lucko.luckperms.sponge.messaging.SpongeMessagingFactory; import me.lucko.luckperms.sponge.messaging.SpongeMessagingFactory;
@ -93,10 +96,10 @@ import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order; import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.game.state.GamePostInitializationEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent; import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.scheduler.AsynchronousExecutor; import org.spongepowered.api.scheduler.AsynchronousExecutor;
import org.spongepowered.api.scheduler.Scheduler; import org.spongepowered.api.scheduler.Scheduler;
@ -109,9 +112,7 @@ import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.AbstractCollection; import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -121,7 +122,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors; import java.util.stream.Stream;
/** /**
* LuckPerms implementation for the Sponge API. * LuckPerms implementation for the Sponge API.
@ -157,18 +158,21 @@ public class LPSpongePlugin implements LuckPermsPlugin {
@AsynchronousExecutor @AsynchronousExecutor
private SpongeExecutorService asyncExecutorService; private SpongeExecutorService asyncExecutorService;
@Inject
private PluginContainer pluginContainer;
private boolean lateLoad = false; private boolean lateLoad = false;
private long startTime; private long startTime;
private LuckPermsScheduler scheduler; private SchedulerAdapter scheduler;
private SpongeCommand commandManager; private SpongeCommandExecutor commandManager;
private LuckPermsConfiguration configuration; private LuckPermsConfiguration configuration;
private SpongeUserManager userManager; private SpongeUserManager userManager;
private SpongeGroupManager groupManager; private SpongeGroupManager groupManager;
private TrackManager trackManager; private TrackManager trackManager;
private Storage storage; private Storage storage;
private FileWatcher fileWatcher = null; private FileWatcher fileWatcher = null;
private InternalMessagingService messagingService = null; private ExtendedMessagingService messagingService = null;
private UuidCache uuidCache; private UuidCache uuidCache;
private ApiProvider apiProvider; private ApiProvider apiProvider;
private me.lucko.luckperms.api.Logger log; private me.lucko.luckperms.api.Logger log;
@ -187,7 +191,7 @@ public class LPSpongePlugin implements LuckPermsPlugin {
@Listener(order = Order.FIRST) @Listener(order = Order.FIRST)
public void onEnable(GamePreInitializationEvent event) { public void onEnable(GamePreInitializationEvent event) {
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
scheduler = new LPSpongeScheduler(this); scheduler = new SpongeSchedulerAdapter(this);
localeManager = new NoopLocaleManager(); localeManager = new NoopLocaleManager();
senderFactory = new SpongeSenderFactory(this); senderFactory = new SpongeSenderFactory(this);
log = new SenderLogger(this, getConsoleSender()); log = new SenderLogger(this, getConsoleSender());
@ -198,15 +202,15 @@ public class LPSpongePlugin implements LuckPermsPlugin {
logDispatcher = new LogDispatcher(this); logDispatcher = new LogDispatcher(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new SpongeConfig(this); configuration = new AbstractConfiguration(this, new SpongeConfigAdapter(this));
configuration.init(); configuration.init();
configuration.loadAll();
Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2); Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2);
DependencyManager.loadStorageDependencies(this, storageTypes); DependencyManager.loadStorageDependencies(this, storageTypes);
// register events // register events
game.getEventManager().registerListeners(this, new SpongeListener(this)); game.getEventManager().registerListeners(this, new SpongeConnectionListener(this));
game.getEventManager().registerListeners(this, new SpongePlatformListener(this));
if (getConfiguration().get(ConfigKeys.WATCH_FILES)) { if (getConfiguration().get(ConfigKeys.WATCH_FILES)) {
fileWatcher = new FileWatcher(this); fileWatcher = new FileWatcher(this);
@ -228,7 +232,7 @@ public class LPSpongePlugin implements LuckPermsPlugin {
// register commands // register commands
CommandManager cmdService = game.getCommandManager(); CommandManager cmdService = game.getCommandManager();
commandManager = new SpongeCommand(this); commandManager = new SpongeCommandExecutor(this);
cmdService.register(this, commandManager, "luckperms", "lp", "perm", "perms", "permission", "permissions"); cmdService.register(this, commandManager, "luckperms", "lp", "perm", "perms", "permission", "permissions");
// load internal managers // load internal managers
@ -281,6 +285,11 @@ public class LPSpongePlugin implements LuckPermsPlugin {
scheduler.asyncRepeating(new CacheHousekeepingTask(this), 2400L); scheduler.asyncRepeating(new CacheHousekeepingTask(this), 2400L);
scheduler.asyncRepeating(new ServiceCacheHousekeepingTask(service), 2400L); scheduler.asyncRepeating(new ServiceCacheHousekeepingTask(service), 2400L);
// register permissions
for (CommandPermission perm : CommandPermission.values()) {
service.registerPermissionDescription(perm.getPermission(), null, pluginContainer);
}
getLog().info("Successfully enabled. (took " + (System.currentTimeMillis() - startTime) + "ms)"); getLog().info("Successfully enabled. (took " + (System.currentTimeMillis() - startTime) + "ms)");
} }
@ -319,19 +328,6 @@ public class LPSpongePlugin implements LuckPermsPlugin {
getLog().info("Goodbye!"); getLog().info("Goodbye!");
} }
@Listener
public void onPostInit(GamePostInitializationEvent event) {
// register permissions
LuckPermsService service = this.service;
if (service == null) {
return;
}
for (CommandPermission perm : CommandPermission.values()) {
registerPermission(service, perm.getPermission());
}
}
@Override @Override
public void onPostUpdate() { public void onPostUpdate() {
for (LPSubjectCollection collection : service.getLoadedCollections().values()) { for (LPSubjectCollection collection : service.getLoadedCollections().values()) {
@ -342,6 +338,15 @@ public class LPSpongePlugin implements LuckPermsPlugin {
service.invalidateAllCaches(LPSubject.CacheLevel.PARENT); service.invalidateAllCaches(LPSubject.CacheLevel.PARENT);
} }
@Override
public Optional<ExtendedMessagingService> getMessagingService() {
return Optional.ofNullable(messagingService);
}
public Optional<FileWatcher> getFileWatcher() {
return Optional.ofNullable(fileWatcher);
}
@Override @Override
public File getDataDirectory() { public File getDataDirectory() {
File base = configDir.toFile().getParentFile().getParentFile(); File base = configDir.toFile().getParentFile().getParentFile();
@ -422,13 +427,13 @@ public class LPSpongePlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<String> getPlayerList() { public Stream<String> getPlayerList() {
return game.isServerAvailable() ? game.getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()) : new ArrayList<>(); return game.isServerAvailable() ? game.getServer().getOnlinePlayers().stream().map(Player::getName) : Stream.empty();
} }
@Override @Override
public Set<UUID> getOnlinePlayers() { public Stream<UUID> getOnlinePlayers() {
return game.isServerAvailable() ? game.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).collect(Collectors.toSet()) : new HashSet<>(); return game.isServerAvailable() ? game.getServer().getOnlinePlayers().stream().map(Player::getUniqueId) : Stream.empty();
} }
@Override @Override
@ -437,14 +442,15 @@ public class LPSpongePlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getOnlineSenders() { public Stream<Sender> getOnlineSenders() {
if (!game.isServerAvailable()) { if (!game.isServerAvailable()) {
return new ArrayList<>(); return Stream.empty();
} }
return game.getServer().getOnlinePlayers().stream() return Stream.concat(
.map(s -> getSenderFactory().wrap(s)) Stream.of(getConsoleSender()),
.collect(Collectors.toList()); game.getServer().getOnlinePlayers().stream().map(s -> getSenderFactory().wrap(s))
);
} }
@Override @Override
@ -496,7 +502,4 @@ public class LPSpongePlugin implements LuckPermsPlugin {
return map; return map;
} }
private void registerPermission(LuckPermsService p, String node) {
p.registerPermissionDescription(node, null, game.getPluginManager().fromInstance(this).get());
}
} }

View File

@ -28,10 +28,10 @@ package me.lucko.luckperms.sponge;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import me.lucko.luckperms.common.commands.CommandManager; import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.commands.utils.Util;
import org.spongepowered.api.command.CommandCallable; import org.spongepowered.api.command.CommandCallable;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.Player;
@ -46,49 +46,31 @@ import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class SpongeCommand extends CommandManager implements CommandCallable { public class SpongeCommandExecutor extends CommandManager implements CommandCallable {
private static final Splitter ARGUMENT_SPLITTER = Splitter.on(COMMAND_SEPARATOR_PATTERN).omitEmptyStrings();
private final LPSpongePlugin plugin; private final LPSpongePlugin plugin;
SpongeCommand(LPSpongePlugin plugin) { SpongeCommandExecutor(LPSpongePlugin plugin) {
super(plugin); super(plugin);
this.plugin = plugin; this.plugin = plugin;
} }
private List<String> processArgs(CommandSource source, String s) {
List<String> args = Util.stripQuotes(Splitter.on(COMMAND_SEPARATOR_PATTERN).omitEmptyStrings().splitToList(s));
// resolve selectors
ListIterator<String> it = args.listIterator();
while (it.hasNext()) {
String element = it.next();
if (element.startsWith("@")) {
try {
Player ret = Selector.parse(element).resolve(source).stream()
.filter(e -> e instanceof Player)
.map(e -> ((Player) e))
.findFirst().orElse(null);
if (ret != null) {
it.set(ret.getUniqueId().toString());
}
} catch (IllegalArgumentException e) {
// ignored
}
}
}
return args;
}
@Override @Override
public CommandResult process(CommandSource source, String s) throws CommandException { public CommandResult process(CommandSource source, String s) {
onCommand(plugin.getSenderFactory().wrap(source), "lp", processArgs(source, s)); Sender lpSender = plugin.getSenderFactory().wrap(source);
List<String> arguments = processSelectors(source, Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(s)));
onCommand(lpSender, "lp", arguments);
return CommandResult.success(); return CommandResult.success();
} }
@Override @Override
public List<String> getSuggestions(CommandSource source, String s, @Nullable Location<World> location) throws CommandException { public List<String> getSuggestions(CommandSource source, String s, @Nullable Location<World> location) {
return onTabComplete(plugin.getSenderFactory().wrap(source), processArgs(source, s)); Sender lpSender = plugin.getSenderFactory().wrap(source);
List<String> arguments = processSelectors(source, Util.stripQuotes(ARGUMENT_SPLITTER.splitToList(s)));
return onTabComplete(lpSender, arguments);
} }
@Override @Override
@ -110,4 +92,27 @@ public class SpongeCommand extends CommandManager implements CommandCallable {
public Text getUsage(CommandSource source) { public Text getUsage(CommandSource source) {
return Text.of("/luckperms"); return Text.of("/luckperms");
} }
private List<String> processSelectors(CommandSource source, List<String> args) {
ListIterator<String> it = args.listIterator();
while (it.hasNext()) {
String element = it.next();
if (element.startsWith("@")) {
try {
Player ret = Selector.parse(element).resolve(source).stream()
.filter(e -> e instanceof Player)
.map(e -> ((Player) e))
.findFirst().orElse(null);
if (ret != null) {
it.set(ret.getUniqueId().toString());
}
} catch (IllegalArgumentException e) {
// ignored
}
}
}
return args;
}
} }

View File

@ -30,7 +30,7 @@ import lombok.RequiredArgsConstructor;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import me.lucko.luckperms.common.config.AbstractConfiguration; import me.lucko.luckperms.common.config.ConfigurationAdapter;
import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.SimpleConfigurationNode; import ninja.leaping.configurate.SimpleConfigurationNode;
@ -49,7 +49,7 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@RequiredArgsConstructor @RequiredArgsConstructor
public class SpongeConfig extends AbstractConfiguration { public class SpongeConfigAdapter implements ConfigurationAdapter {
@Getter @Getter
private final LPSpongePlugin plugin; private final LPSpongePlugin plugin;

View File

@ -25,7 +25,7 @@
package me.lucko.luckperms.sponge; package me.lucko.luckperms.sponge;
import me.lucko.luckperms.common.plugin.LuckPermsScheduler; import me.lucko.luckperms.common.plugin.SchedulerAdapter;
import org.spongepowered.api.scheduler.Task; import org.spongepowered.api.scheduler.Task;
@ -33,11 +33,11 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
public class LPSpongeScheduler implements LuckPermsScheduler { public class SpongeSchedulerAdapter implements SchedulerAdapter {
private final LPSpongePlugin plugin; private final LPSpongePlugin plugin;
private final Set<Task> tasks = ConcurrentHashMap.newKeySet(); private final Set<Task> tasks = ConcurrentHashMap.newKeySet();
public LPSpongeScheduler(LPSpongePlugin plugin) { public SpongeSchedulerAdapter(LPSpongePlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
} }

View File

@ -71,11 +71,8 @@ public class SpongeCalculatorFactory extends AbstractCalculatorFactory {
processors.add(new DefaultsProcessor(plugin.getService(), contexts.getContexts().makeImmutable())); processors.add(new DefaultsProcessor(plugin.getService(), contexts.getContexts().makeImmutable()));
} }
return registerCalculator(new PermissionCalculator( PermissionCalculatorMetadata meta = PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts());
plugin, return registerCalculator(new PermissionCalculator(plugin, meta, processors.build()));
PermissionCalculatorMetadata.of(user.getFriendlyName(), contexts.getContexts()),
processors.build()
));
} }
@Override @Override

View File

@ -23,7 +23,7 @@
* SOFTWARE. * SOFTWARE.
*/ */
package me.lucko.luckperms.sponge; package me.lucko.luckperms.sponge.listeners;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -32,11 +32,10 @@ import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.utils.LoginHelper; import me.lucko.luckperms.common.utils.LoginHelper;
import me.lucko.luckperms.common.utils.UuidCache; import me.lucko.luckperms.common.utils.UuidCache;
import me.lucko.luckperms.sponge.LPSpongePlugin;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order; import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.command.SendCommandEvent;
import org.spongepowered.api.event.filter.IsCancelled; import org.spongepowered.api.event.filter.IsCancelled;
import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.profile.GameProfile;
@ -49,7 +48,7 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
@RequiredArgsConstructor @RequiredArgsConstructor
public class SpongeListener { public class SpongeConnectionListener {
private final LPSpongePlugin plugin; private final LPSpongePlugin plugin;
private final Set<UUID> deniedAsyncLogin = Collections.synchronizedSet(new HashSet<>()); private final Set<UUID> deniedAsyncLogin = Collections.synchronizedSet(new HashSet<>());
@ -175,7 +174,7 @@ public class SpongeListener {
@Listener(order = Order.EARLY) @Listener(order = Order.EARLY)
public void onClientJoin(ClientConnectionEvent.Join e) { public void onClientJoin(ClientConnectionEvent.Join e) {
// Refresh permissions again // Refresh permissions again
plugin.doAsync(() -> LoginHelper.refreshPlayer(plugin, e.getTargetEntity().getUniqueId())); plugin.getScheduler().doAsync(() -> LoginHelper.refreshPlayer(plugin, e.getTargetEntity().getUniqueId()));
} }
@Listener(order = Order.POST) @Listener(order = Order.POST)
@ -190,14 +189,4 @@ public class SpongeListener {
cache.clearCache(e.getTargetEntity().getUniqueId()); cache.clearCache(e.getTargetEntity().getUniqueId());
} }
@Listener
public void onSendCommand(SendCommandEvent e) {
CommandSource source = e.getCause().first(CommandSource.class).orElse(null);
if (source == null) return;
final String name = e.getCommand().toLowerCase();
if (((name.equals("op") || name.equals("minecraft:op")) && source.hasPermission("minecraft.command.op")) || ((name.equals("deop") || name.equals("minecraft:deop")) && source.hasPermission("minecraft.command.deop"))) {
Message.OP_DISABLED_SPONGE.send(plugin.getSenderFactory().wrap(source));
}
}
} }

View File

@ -0,0 +1,51 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* 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.sponge.listeners;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.sponge.LPSpongePlugin;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.command.SendCommandEvent;
@RequiredArgsConstructor
public class SpongePlatformListener {
private final LPSpongePlugin plugin;
@Listener
public void onSendCommand(SendCommandEvent e) {
CommandSource source = e.getCause().first(CommandSource.class).orElse(null);
if (source == null) return;
final String name = e.getCommand().toLowerCase();
if (((name.equals("op") || name.equals("minecraft:op")) && source.hasPermission("minecraft.command.op")) || ((name.equals("deop") || name.equals("minecraft:deop")) && source.hasPermission("minecraft.command.deop"))) {
Message.OP_DISABLED_SPONGE.send(plugin.getSenderFactory().wrap(source));
}
}
}

View File

@ -198,12 +198,10 @@ public class SpongeUserManager implements UserManager, LPSubjectCollection {
@Override @Override
public CompletableFuture<Void> updateAllUsers() { public CompletableFuture<Void> updateAllUsers() {
return CompletableFuture.supplyAsync(plugin::getOnlinePlayers, plugin.getScheduler().sync()) return CompletableFuture.supplyAsync(plugin::getOnlinePlayers, plugin.getScheduler().sync())
.thenAcceptAsync(players -> { .thenAcceptAsync(players -> players.forEach(uuid -> {
for (UUID uuid : players) { UUID internal = plugin.getUuidCache().getUUID(uuid);
UUID internal = plugin.getUuidCache().getUUID(uuid); plugin.getStorage().loadUser(internal, "null").join();
plugin.getStorage().loadUser(internal, "null").join(); }), plugin.getScheduler().async());
}
}, plugin.getScheduler().async());
} }
/* ------------------------------------------ /* ------------------------------------------

View File

@ -28,6 +28,7 @@ package me.lucko.luckperms.sponge.messaging;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import me.lucko.luckperms.common.messaging.AbstractMessagingService; import me.lucko.luckperms.common.messaging.AbstractMessagingService;
import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.sponge.LPSpongePlugin; import me.lucko.luckperms.sponge.LPSpongePlugin;
import org.spongepowered.api.Platform; import org.spongepowered.api.Platform;
@ -41,7 +42,7 @@ import java.util.Collection;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* An implementation of {@link me.lucko.luckperms.api.MessagingService} using the plugin messaging channels. * An implementation of {@link ExtendedMessagingService} using the plugin messaging channels.
*/ */
public class BungeeMessagingService extends AbstractMessagingService implements RawDataListener { public class BungeeMessagingService extends AbstractMessagingService implements RawDataListener {
private final LPSpongePlugin plugin; private final LPSpongePlugin plugin;
@ -65,7 +66,7 @@ public class BungeeMessagingService extends AbstractMessagingService implements
} }
@Override @Override
protected void sendMessage(String channel, String message) { protected void sendMessage(String message) {
plugin.getSpongeScheduler().createTaskBuilder().interval(10, TimeUnit.SECONDS).execute(task -> { plugin.getSpongeScheduler().createTaskBuilder().interval(10, TimeUnit.SECONDS).execute(task -> {
if (!plugin.getGame().isServerAvailable()) { if (!plugin.getGame().isServerAvailable()) {
return; return;
@ -86,6 +87,6 @@ public class BungeeMessagingService extends AbstractMessagingService implements
@Override @Override
public void handlePayload(ChannelBuf buf, RemoteConnection connection, Platform.Type type) { public void handlePayload(ChannelBuf buf, RemoteConnection connection, Platform.Type type) {
String msg = buf.readUTF(); String msg = buf.readUTF();
onMessage(CHANNEL, msg, null); onMessage(msg, null);
} }
} }

View File

@ -25,7 +25,7 @@
package me.lucko.luckperms.sponge.messaging; package me.lucko.luckperms.sponge.messaging;
import me.lucko.luckperms.common.messaging.InternalMessagingService; import me.lucko.luckperms.common.messaging.ExtendedMessagingService;
import me.lucko.luckperms.common.messaging.MessagingFactory; import me.lucko.luckperms.common.messaging.MessagingFactory;
import me.lucko.luckperms.sponge.LPSpongePlugin; import me.lucko.luckperms.sponge.LPSpongePlugin;
@ -35,7 +35,7 @@ public class SpongeMessagingFactory extends MessagingFactory<LPSpongePlugin> {
} }
@Override @Override
protected InternalMessagingService getServiceFor(String messagingType) { protected ExtendedMessagingService getServiceFor(String messagingType) {
if (messagingType.equals("bungee")) { if (messagingType.equals("bungee")) {
BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin()); BungeeMessagingService bungeeMessaging = new BungeeMessagingService(getPlugin());
bungeeMessaging.init(); bungeeMessaging.init();

View File

@ -79,16 +79,14 @@ public class PersistedSubject implements LPSubject {
.expireAfterAccess(20, TimeUnit.MINUTES) .expireAfterAccess(20, TimeUnit.MINUTES)
.build(lookup -> lookupOptionValue(lookup.getContexts(), lookup.getKey())); .build(lookup -> lookupOptionValue(lookup.getContexts(), lookup.getKey()));
private final BufferedRequest<Void> saveBuffer = new BufferedRequest<Void>(1000L, 500L, r -> PersistedSubject.this.service.getPlugin().doAsync(r)) { private final BufferedRequest<Void> saveBuffer = new BufferedRequest<Void>(1000L, 500L, r -> PersistedSubject.this.service.getPlugin().getScheduler().doAsync(r)) {
@Override @Override
protected Void perform() { protected Void perform() {
service.getPlugin().doAsync(() -> { try {
try { service.getStorage().saveToFile(PersistedSubject.this);
service.getStorage().saveToFile(PersistedSubject.this); } catch (IOException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); }
}
});
return null; return null;
} }
}; };