diff --git a/api/src/main/java/me/lucko/luckperms/api/Node.java b/api/src/main/java/me/lucko/luckperms/api/Node.java index 78428088c..99dcc2d3e 100644 --- a/api/src/main/java/me/lucko/luckperms/api/Node.java +++ b/api/src/main/java/me/lucko/luckperms/api/Node.java @@ -85,15 +85,35 @@ public interface Node extends Map.Entry { Optional getWorld(); /** + * Returns if this node is server specific + * * @return true if this node is server specific */ boolean isServerSpecific(); /** + * Returns if this node is server specific + * * @return true if this node is server specific */ boolean isWorldSpecific(); + /** + * Returns if this node applies globally, and has no specific context + * + * @return true if this node applies globally, and has no specific context + * @since 3.1 + */ + boolean appliesGlobally(); + + /** + * Returns if this node has any specific context in order to apply. + * + * @return true if this node has specific context + * @since 3.1 + */ + boolean hasSpecificContext(); + /** * If this node should apply on a specific server * @@ -222,22 +242,30 @@ public interface Node extends Map.Entry { * Converts this node into a serialized form * * @return a serialized node string + * @deprecated because this serialized form is no longer used by the implementation. */ + @Deprecated String toSerializedNode(); /** + * Returns if this is a group node + * * @return true if this is a group node */ boolean isGroupNode(); /** + * Returns the name of the group + * * @return the name of the group * @throws IllegalStateException if this is not a group node. See {@link #isGroupNode()} */ String getGroupName(); /** - * @return true is this node is a wildcard node + * Returns if this node is a wildcard node + * + * @return true if this node is a wildcard node */ boolean isWildcard(); @@ -250,6 +278,8 @@ public interface Node extends Map.Entry { int getWildcardLevel(); /** + * Returns if this node is a meta node + * * @return true if this node is a meta node */ boolean isMeta(); diff --git a/api/src/main/java/me/lucko/luckperms/api/context/ContextSet.java b/api/src/main/java/me/lucko/luckperms/api/context/ContextSet.java index 14fa97680..9a95b3835 100644 --- a/api/src/main/java/me/lucko/luckperms/api/context/ContextSet.java +++ b/api/src/main/java/me/lucko/luckperms/api/context/ContextSet.java @@ -37,7 +37,7 @@ import java.util.Set; public interface ContextSet { /** - * Make a singleton ImmutableContextSet from a context pair + * Creates an ImmutableContextSet from a context pair * * @param key the key * @param value the value @@ -49,7 +49,22 @@ public interface ContextSet { } /** - * Creates a ImmutableContextSet from an existing map + * Creates an ImmutableContextSet from two context pairs + * + * @param key1 the first key + * @param value1 the first value + * @param key2 the second key + * @param value2 the second value + * @return a new ImmutableContextSet containing the two pairs + * @throws NullPointerException if any of the keys or values are null + * @since 3.1 + */ + static ImmutableContextSet of(String key1, String value1, String key2, String value2) { + return ImmutableContextSet.of(key1, value1, key2, value2); + } + + /** + * Creates an ImmutableContextSet from an existing map * * @param map the map to copy from * @return a new ImmutableContextSet representing the pairs from the map @@ -60,7 +75,7 @@ public interface ContextSet { } /** - * Creates a ImmutableContextSet from an existing iterable of Map Entries + * Creates an ImmutableContextSet from an existing iterable of Map Entries * * @param iterable the iterable to copy from * @return a new ImmutableContextSet representing the pairs in the iterable @@ -71,7 +86,7 @@ public interface ContextSet { } /** - * Creates a ImmutableContextSet from an existing multimap + * Creates an ImmutableContextSet from an existing multimap * * @param multimap the multimap to copy from * @return a new ImmutableContextSet representing the pairs in the multimap @@ -83,7 +98,7 @@ public interface ContextSet { } /** - * Creates a new ImmutableContextSet from an existing set. + * Creates an new ImmutableContextSet from an existing set. * Only really useful for converting between mutable and immutable types. * * @param contextSet the context set to copy from @@ -173,6 +188,7 @@ public interface ContextSet { * * @param key the key to find values for * @return an optional containing any match + * @since 3.1 */ default Optional getAnyValue(String key) { return getValues(key).stream().findAny(); @@ -203,6 +219,7 @@ public interface ContextSet { * * @param other the other set to check * @return true if all entries in this set are also in the other set + * @since 3.1 */ default boolean isSatisfiedBy(ContextSet other) { if (this.isEmpty()) { diff --git a/api/src/main/java/me/lucko/luckperms/api/context/ImmutableContextSet.java b/api/src/main/java/me/lucko/luckperms/api/context/ImmutableContextSet.java index c58e968cc..f0d057d09 100644 --- a/api/src/main/java/me/lucko/luckperms/api/context/ImmutableContextSet.java +++ b/api/src/main/java/me/lucko/luckperms/api/context/ImmutableContextSet.java @@ -41,7 +41,7 @@ public final class ImmutableContextSet implements ContextSet { private static final ImmutableContextSet EMPTY = new ImmutableContextSet(ImmutableSetMultimap.of()); /** - * Make a singleton ImmutableContextSet from a context pair + * Creates an ImmutableContextSet from a context pair * * @param key the key * @param value the value @@ -60,7 +60,35 @@ public final class ImmutableContextSet implements ContextSet { } /** - * Creates a ImmutableContextSet from an existing map + * Creates an ImmutableContextSet from two context pairs + * + * @param key1 the first key + * @param value1 the first value + * @param key2 the second key + * @param value2 the second value + * @return a new ImmutableContextSet containing the two pairs + * @throws NullPointerException if any of the keys or values are null + * @since 3.1 + */ + public static ImmutableContextSet of(String key1, String value1, String key2, String value2) { + if (key1 == null) { + throw new NullPointerException("key1"); + } + if (value1 == null) { + throw new NullPointerException("value1"); + } + if (key2 == null) { + throw new NullPointerException("key2"); + } + if (value2 == null) { + throw new NullPointerException("value2"); + } + + return new ImmutableContextSet(ImmutableSetMultimap.of(key1.toLowerCase(), value1, key2.toLowerCase(), value2)); + } + + /** + * Creates an ImmutableContextSet from an existing map * * @param map the map to copy from * @return a new ImmutableContextSet representing the pairs from the map @@ -80,7 +108,7 @@ public final class ImmutableContextSet implements ContextSet { } /** - * Creates a ImmutableContextSet from an existing iterable of Map Entries + * Creates an ImmutableContextSet from an existing iterable of Map Entries * * @param iterable the iterable to copy from * @return a new ImmutableContextSet representing the pairs in the iterable @@ -95,7 +123,7 @@ public final class ImmutableContextSet implements ContextSet { } /** - * Creates a ImmutableContextSet from an existing multimap + * Creates an ImmutableContextSet from an existing multimap * * @param multimap the multimap to copy from * @return a new ImmutableContextSet representing the pairs in the multimap @@ -122,7 +150,7 @@ public final class ImmutableContextSet implements ContextSet { } /** - * Creates a new empty ContextSet. + * Creates an new empty ContextSet. * * @return a new ContextSet */ diff --git a/api/src/main/java/me/lucko/luckperms/api/context/MutableContextSet.java b/api/src/main/java/me/lucko/luckperms/api/context/MutableContextSet.java index e42616e5f..b4e66e049 100644 --- a/api/src/main/java/me/lucko/luckperms/api/context/MutableContextSet.java +++ b/api/src/main/java/me/lucko/luckperms/api/context/MutableContextSet.java @@ -62,6 +62,36 @@ public final class MutableContextSet implements ContextSet { return set; } + /** + * Makes a MutableContextSet from two context pairs + * + * @param key1 the first key + * @param value1 the first value + * @param key2 the second key + * @param value2 the second value + * @return a new MutableContextSet containing the two pairs + * @throws NullPointerException if any of the keys or values are null + * @since 3.1 + */ + public static MutableContextSet of(String key1, String value1, String key2, String value2) { + if (key1 == null) { + throw new NullPointerException("key1"); + } + if (value1 == null) { + throw new NullPointerException("value1"); + } + if (key2 == null) { + throw new NullPointerException("key2"); + } + if (value2 == null) { + throw new NullPointerException("value2"); + } + + MutableContextSet ret = singleton(key1, value1); + ret.add(key2, value2); + return ret; + } + /** * Creates a MutableContextSet from an existing map * diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/compat/MessageHandler.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/compat/MessageHandler.java index 2749d4458..65164e46e 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/compat/MessageHandler.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/compat/MessageHandler.java @@ -39,7 +39,7 @@ public class MessageHandler { public void sendJsonMessage(CommandSender sender, FancyMessage message) { if (ReflectionUtil.isChatCompatible() && sender instanceof Player) { Player player = (Player) sender; - String json = message.toJSONString(); + String json = message.exportToJson(); // Try Bukkit. if (bukkitHandler.sendJsonMessage(player, json)) { diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationBPermissions.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationBPermissions.java index 5a1b41763..65b2fb543 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationBPermissions.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationBPermissions.java @@ -189,11 +189,11 @@ public class MigrationBPermissions extends SubCommand { private static void migrateHolder(World world, Calculable c, PermissionHolder holder) { // Migrate the groups permissions in this world for (Permission p : c.getPermissions()) { - holder.setPermissionUnchecked(NodeFactory.make(p.name(), p.isTrue(), "global", world.getName())); + holder.setPermission(NodeFactory.make(p.name(), p.isTrue(), "global", world.getName())); // Include any child permissions for (Map.Entry child : p.getChildren().entrySet()) { - holder.setPermissionUnchecked(NodeFactory.make(child.getKey(), child.getValue(), "global", world.getName())); + holder.setPermission(NodeFactory.make(child.getKey(), child.getValue(), "global", world.getName())); } } @@ -204,17 +204,17 @@ public class MigrationBPermissions extends SubCommand { parentName = "default"; } - holder.setPermissionUnchecked(NodeFactory.make("group." + parentName, true, "global", world.getName())); + holder.setPermission(NodeFactory.make("group." + parentName, true, "global", world.getName())); } // Migrate existing meta for (Map.Entry meta : c.getMeta().entrySet()) { if (meta.getKey().equalsIgnoreCase("prefix") || meta.getKey().equalsIgnoreCase("suffix")) { - holder.setPermissionUnchecked(NodeFactory.makeChatMetaNode(meta.getKey().equalsIgnoreCase("prefix"), c.getPriority(), meta.getValue()).setWorld(world.getName()).build()); + holder.setPermission(NodeFactory.makeChatMetaNode(meta.getKey().equalsIgnoreCase("prefix"), c.getPriority(), meta.getValue()).setWorld(world.getName()).build()); continue; } - holder.setPermissionUnchecked(NodeFactory.makeMetaNode(meta.getKey(), meta.getValue()).setWorld(world.getName()).build()); + holder.setPermission(NodeFactory.makeMetaNode(meta.getKey(), meta.getValue()).setWorld(world.getName()).build()); } } } diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationGroupManager.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationGroupManager.java index 74443d092..db2b353ed 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationGroupManager.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationGroupManager.java @@ -97,11 +97,11 @@ public class MigrationGroupManager extends SubCommand { me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(groupName); for (String node : g.getPermissionList()) { - group.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); + group.setPermission(MigrationUtils.parseNode(node, true).build()); } for (String s : g.getInherits()) { - group.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(s))); + group.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(s))); } plugin.getStorage().saveGroup(group); @@ -217,7 +217,7 @@ public class MigrationGroupManager extends SubCommand { me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(e.getKey()); for (Node node : e.getValue()) { - group.setPermissionUnchecked(node); + group.setPermission(node); } plugin.getStorage().saveGroup(group); @@ -232,14 +232,14 @@ public class MigrationGroupManager extends SubCommand { me.lucko.luckperms.common.core.model.User user = plugin.getUserManager().get(e.getKey()); for (Node node : e.getValue()) { - user.setPermissionUnchecked(node); + user.setPermission(node); } String primaryGroup = primaryGroups.get(e.getKey()); if (primaryGroup != null) { - user.setPermissionUnchecked(NodeFactory.make("group." + primaryGroup)); + user.setPermission(NodeFactory.make("group." + primaryGroup)); user.getPrimaryGroup().setStoredValue(primaryGroup); - user.unsetPermissionUnchecked(NodeFactory.make("group.default")); + user.unsetPermission(NodeFactory.make("group.default")); } plugin.getStorage().saveUser(user); diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPermissionsEx.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPermissionsEx.java index 9923be1cd..018df9204 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPermissionsEx.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPermissionsEx.java @@ -106,7 +106,7 @@ public class MigrationPermissionsEx extends SubCommand { try { for (String node : group.getOwnPermissions(null)) { - lpGroup.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); + lpGroup.setPermission(MigrationUtils.parseNode(node, true).build()); } } catch (NullPointerException ignored) { // No docs on if #getOwnPermissions(null) is ok. Should be fine though. @@ -114,17 +114,17 @@ public class MigrationPermissionsEx extends SubCommand { for (String world : worlds) { for (String node : group.getOwnPermissions(world)) { - lpGroup.setPermissionUnchecked(MigrationUtils.parseNode(node, true).setWorld(world.toLowerCase()).build()); + lpGroup.setPermission(MigrationUtils.parseNode(node, true).setWorld(world.toLowerCase()).build()); } } for (PermissionGroup g : group.getParents()) { - lpGroup.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(g.getName()))); + lpGroup.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(g.getName()))); } for (String world : worlds) { for (PermissionGroup g : group.getParents(world)) { - lpGroup.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(g.getName()), true, "global", world.toLowerCase())); + lpGroup.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(g.getName()), true, "global", world.toLowerCase())); } } @@ -132,11 +132,11 @@ public class MigrationPermissionsEx extends SubCommand { String suffix = group.getOwnSuffix(); if (prefix != null && !prefix.equals("")) { - lpGroup.setPermissionUnchecked(NodeFactory.makePrefixNode(groupWeight, prefix).build()); + lpGroup.setPermission(NodeFactory.makePrefixNode(groupWeight, prefix).build()); } if (suffix != null && !suffix.equals("")) { - lpGroup.setPermissionUnchecked(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); + lpGroup.setPermission(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); } plugin.getStorage().saveGroup(lpGroup); @@ -176,7 +176,7 @@ public class MigrationPermissionsEx extends SubCommand { try { for (String node : user.getOwnPermissions(null)) { - lpUser.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); + lpUser.setPermission(MigrationUtils.parseNode(node, true).build()); } } catch (NullPointerException ignored) { // No docs on if #getOwnPermissions(null) is ok. Should be fine though. @@ -184,17 +184,17 @@ public class MigrationPermissionsEx extends SubCommand { for (String world : worlds) { for (String node : user.getOwnPermissions(world)) { - lpUser.setPermissionUnchecked(MigrationUtils.parseNode(node, true).setWorld(world.toLowerCase()).build()); + lpUser.setPermission(MigrationUtils.parseNode(node, true).setWorld(world.toLowerCase()).build()); } } for (String g : user.getGroupNames()) { - lpUser.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(g))); + lpUser.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(g))); } for (String world : worlds) { for (String g : user.getGroupNames(world)) { - lpUser.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(g), true, "global", world.toLowerCase())); + lpUser.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(g), true, "global", world.toLowerCase())); } } @@ -202,11 +202,11 @@ public class MigrationPermissionsEx extends SubCommand { String suffix = user.getOwnSuffix(); if (prefix != null && !prefix.equals("")) { - lpUser.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); + lpUser.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build()); } if (suffix != null && !suffix.equals("")) { - lpUser.setPermissionUnchecked(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); + lpUser.setPermission(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); } // Lowest rank is the highest group #logic @@ -220,9 +220,9 @@ public class MigrationPermissionsEx extends SubCommand { } if (primary != null && !primary.equalsIgnoreCase("default")) { - lpUser.setPermissionUnchecked(NodeFactory.make("group." + primary.toLowerCase())); + lpUser.setPermission(NodeFactory.make("group." + primary.toLowerCase())); lpUser.getPrimaryGroup().setStoredValue(primary); - lpUser.unsetPermissionUnchecked(NodeFactory.make("group.default")); + lpUser.unsetPermission(NodeFactory.make("group.default")); } plugin.getUserManager().cleanup(lpUser); diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPowerfulPerms.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPowerfulPerms.java index 630c5ba6e..c0afaed39 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPowerfulPerms.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationPowerfulPerms.java @@ -180,7 +180,7 @@ public class MigrationPowerfulPerms extends SubCommand { } for (Group parent : g.getParents()) { - group.setPermissionUnchecked(NodeFactory.make("group." + parent.getName().toLowerCase(), true)); + group.setPermission(NodeFactory.make("group." + parent.getName().toLowerCase(), true)); } // server --> prefix afaik @@ -191,9 +191,9 @@ public class MigrationPowerfulPerms extends SubCommand { } if (server != null) { - group.setPermissionUnchecked(NodeFactory.makePrefixNode(g.getRank(), prefix.getValue()).setServer(server).build()); + group.setPermission(NodeFactory.makePrefixNode(g.getRank(), prefix.getValue()).setServer(server).build()); } else { - group.setPermissionUnchecked(NodeFactory.makePrefixNode(g.getRank(), prefix.getValue()).build()); + group.setPermission(NodeFactory.makePrefixNode(g.getRank(), prefix.getValue()).build()); } } @@ -204,9 +204,9 @@ public class MigrationPowerfulPerms extends SubCommand { } if (server != null) { - group.setPermissionUnchecked(NodeFactory.makeSuffixNode(g.getRank(), suffix.getValue()).setServer(server).build()); + group.setPermission(NodeFactory.makeSuffixNode(g.getRank(), suffix.getValue()).setServer(server).build()); } else { - group.setPermissionUnchecked(NodeFactory.makeSuffixNode(g.getRank(), suffix.getValue()).build()); + group.setPermission(NodeFactory.makeSuffixNode(g.getRank(), suffix.getValue()).build()); } } @@ -252,16 +252,16 @@ public class MigrationPowerfulPerms extends SubCommand { String suffix = joinFuture(pm.getPlayerOwnSuffix(uuid)); if (prefix != null && !prefix.equals("")) { - user.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); + user.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build()); } if (suffix != null && !suffix.equals("")) { - user.setPermissionUnchecked(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); + user.setPermission(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); } String primary = joinFuture(pm.getPlayerPrimaryGroup(uuid)).getName().toLowerCase(); if (!primary.equals("default")) { - user.setPermissionUnchecked(NodeFactory.make("group." + primary)); + user.setPermission(NodeFactory.make("group." + primary)); user.getPrimaryGroup().setStoredValue(primary); } @@ -316,7 +316,7 @@ public class MigrationPowerfulPerms extends SubCommand { nb.setWorld(world); } - holder.setPermissionUnchecked(nb.build()); + holder.setPermission(nb.build()); } private void applyGroup(PermissionManager pm, PermissionHolder holder, CachedGroup g, String server) { @@ -338,7 +338,7 @@ public class MigrationPowerfulPerms extends SubCommand { nb.setServer(server); } - holder.setPermissionUnchecked(nb.build()); + holder.setPermission(nb.build()); } @SneakyThrows diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationZPermissions.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationZPermissions.java index e9992f3b2..b2455a8c7 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationZPermissions.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/migration/MigrationZPermissions.java @@ -147,9 +147,9 @@ public class MigrationZPermissions extends SubCommand { private void migrateEntity(PermissionHolder holder, PermissionEntity entity, List memberships) { for (Entry e : entity.getPermissions()) { if (e.getWorld() != null && !e.getWorld().getName().equals("")) { - holder.setPermissionUnchecked(MigrationUtils.parseNode(e.getPermission(), true).setWorld(e.getWorld().getName()).build()); + holder.setPermission(MigrationUtils.parseNode(e.getPermission(), true).setWorld(e.getWorld().getName()).build()); } else { - holder.setPermissionUnchecked(MigrationUtils.parseNode(e.getPermission(), true).build()); + holder.setPermission(MigrationUtils.parseNode(e.getPermission(), true).build()); } } @@ -157,12 +157,12 @@ public class MigrationZPermissions extends SubCommand { // entity.getMemberships() doesn't work for groups (always returns 0 records) for (Inheritance inheritance : entity.getInheritancesAsChild()) { if (!inheritance.getParent().getName().equals(holder.getObjectName())) { - holder.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(inheritance.getParent().getName()))); + holder.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(inheritance.getParent().getName()))); } } } else { for (Membership membership : memberships) { - holder.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(membership.getGroup().getDisplayName()))); + holder.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(membership.getGroup().getDisplayName()))); } } @@ -171,9 +171,9 @@ public class MigrationZPermissions extends SubCommand { String key = metadata.getName().toLowerCase(); if (key.equals("prefix") || key.equals("suffix")) { - holder.setPermissionUnchecked(NodeFactory.makeChatMetaNode(key.equals("prefix"), weight, metadata.getStringValue()).build()); + holder.setPermission(NodeFactory.makeChatMetaNode(key.equals("prefix"), weight, metadata.getStringValue()).build()); } else { - holder.setPermissionUnchecked(NodeFactory.makeMetaNode(key, metadata.getStringValue()).build()); + holder.setPermission(NodeFactory.makeMetaNode(key, metadata.getStringValue()).build()); } } } diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultChatHook.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultChatHook.java index fd4dc275a..06ba73eb1 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultChatHook.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultChatHook.java @@ -81,7 +81,7 @@ public class VaultChatHook extends Chat { metaNode.setWorld(finalWorld); } - holder.setPermissionUnchecked(metaNode.build()); + holder.setPermission(metaNode.build()); perms.save(holder); }); } @@ -111,7 +111,7 @@ public class VaultChatHook extends Chat { chatMetaNode.setWorld(finalWorld); } - holder.setPermissionUnchecked(chatMetaNode.build()); + holder.setPermission(chatMetaNode.build()); perms.save(holder); }); } diff --git a/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultPermissionHook.java b/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultPermissionHook.java index e01eecf69..98faa7b5a 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultPermissionHook.java +++ b/bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultPermissionHook.java @@ -30,22 +30,24 @@ import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.Tristate; import me.lucko.luckperms.api.caching.PermissionData; import me.lucko.luckperms.api.context.ContextSet; +import me.lucko.luckperms.api.context.ImmutableContextSet; import me.lucko.luckperms.bukkit.LPBukkitPlugin; import me.lucko.luckperms.common.config.ConfigKeys; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.utils.ExtractedContexts; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import net.milkbowl.vault.permission.Permission; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import java.util.stream.Collectors; /** * LuckPerms Vault Permission implementation @@ -91,15 +93,16 @@ public class VaultPermissionHook extends Permission { */ private CompletableFuture add(String world, PermissionHolder holder, String permission) { return CompletableFuture.runAsync(() -> { - try { - if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { - holder.setPermission(NodeFactory.make(permission, true, getServer(), world)); - } else { - holder.setPermission(NodeFactory.make(permission, true, getServer())); - } + DataMutateResult result; + if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { + result = holder.setPermission(NodeFactory.make(permission, true, getServer(), world)); + } else { + result = holder.setPermission(NodeFactory.make(permission, true, getServer())); + } + if (result.asBoolean()) { save(holder); - } catch (ObjectAlreadyHasException ignored) {} + } }, scheduler); } @@ -112,15 +115,16 @@ public class VaultPermissionHook extends Permission { */ private CompletableFuture remove(String world, PermissionHolder holder, String permission) { return CompletableFuture.runAsync(() -> { - try { - if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { - holder.unsetPermission(NodeFactory.make(permission, getServer(), world)); - } else { - holder.unsetPermission(NodeFactory.make(permission, getServer())); - } + DataMutateResult result; + if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { + result = holder.unsetPermission(NodeFactory.make(permission, getServer(), world)); + } else { + result = holder.unsetPermission(NodeFactory.make(permission, getServer())); + } + if (result.asBoolean()) { save(holder); - } catch (ObjectLacksException ignored) {} + } }, scheduler); } @@ -256,15 +260,16 @@ public class VaultPermissionHook extends Permission { String w = world; scheduler.execute(() -> { - try { - if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { - user.setInheritGroup(group, getServer(), w); - } else { - user.setInheritGroup(group, getServer()); - } + DataMutateResult result; + if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { + result = user.setInheritGroup(group, ImmutableContextSet.of("server", getServer(), "world", w)); + } else { + result = user.setInheritGroup(group, ImmutableContextSet.singleton("server", getServer())); + } + if (result.asBoolean()) { save(user); - } catch (ObjectAlreadyHasException ignored) {} + } }); return true; } @@ -282,15 +287,16 @@ public class VaultPermissionHook extends Permission { String w = world; scheduler.execute(() -> { - try { - if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { - user.unsetInheritGroup(group, getServer(), w); - } else { - user.unsetInheritGroup(group, getServer()); - } + DataMutateResult result; + if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { + result = user.unsetInheritGroup(group, ImmutableContextSet.of("server", getServer(), "world", w)); + } else { + result = user.unsetInheritGroup(group, ImmutableContextSet.singleton("server", getServer())); + } + if (result.asBoolean()) { save(user); - } catch (ObjectLacksException ignored) {} + } }); return true; } @@ -367,7 +373,15 @@ public class VaultPermissionHook extends Permission { } if (isPgoCheckMemberOf()) { - if (!user.getLocalGroups(getServer(), world, isIncludeGlobal()).contains(group.toLowerCase())) { + String finalWorld = world; + List localGroups = user.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .filter(n -> n.shouldApplyOnWorld(finalWorld, isIncludeGlobal(), true)) + .filter(n -> n.shouldApplyOnServer(getServer(), isIncludeGlobal(), true)) + .map(Node::getGroupName) + .collect(Collectors.toList()); + + if (!localGroups.contains(group.toLowerCase())) { continue; } } diff --git a/bungee/src/main/java/me/lucko/luckperms/bungee/BungeeSenderFactory.java b/bungee/src/main/java/me/lucko/luckperms/bungee/BungeeSenderFactory.java index 26966a29f..edeb6aa8a 100644 --- a/bungee/src/main/java/me/lucko/luckperms/bungee/BungeeSenderFactory.java +++ b/bungee/src/main/java/me/lucko/luckperms/bungee/BungeeSenderFactory.java @@ -64,7 +64,7 @@ public class BungeeSenderFactory extends SenderFactory { @Override protected void sendMessage(CommandSender sender, FancyMessage message) { try { - sender.sendMessage(ComponentSerializer.parse(message.toJSONString())); + sender.sendMessage(ComponentSerializer.parse(message.exportToJson())); } catch (Exception e) { sendMessage(sender, message.toOldMessageFormat()); } diff --git a/bungee/src/main/java/me/lucko/luckperms/bungee/migration/MigrationBungeePerms.java b/bungee/src/main/java/me/lucko/luckperms/bungee/migration/MigrationBungeePerms.java index 1648d7bf7..109ce1aed 100644 --- a/bungee/src/main/java/me/lucko/luckperms/bungee/migration/MigrationBungeePerms.java +++ b/bungee/src/main/java/me/lucko/luckperms/bungee/migration/MigrationBungeePerms.java @@ -88,26 +88,26 @@ public class MigrationBungeePerms extends SubCommand { // Migrate global perms for (String perm : g.getPerms()) { - group.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).build()); + group.setPermission(MigrationUtils.parseNode(perm, true).build()); } // Migrate per-server perms for (Map.Entry e : g.getServers().entrySet()) { for (String perm : e.getValue().getPerms()) { - group.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).setWorld(e.getKey()).build()); + group.setPermission(MigrationUtils.parseNode(perm, true).setWorld(e.getKey()).build()); } // Migrate per-world perms for (Map.Entry we : e.getValue().getWorlds().entrySet()) { for (String perm : we.getValue().getPerms()) { - group.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).setServer(e.getKey()).setWorld(we.getKey()).build()); + group.setPermission(MigrationUtils.parseNode(perm, true).setServer(e.getKey()).setWorld(we.getKey()).build()); } } } // Migrate any parent groups for (String inherit : g.getInheritances()) { - group.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(inherit))); + group.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(inherit))); } // Migrate prefix and suffix @@ -115,10 +115,10 @@ public class MigrationBungeePerms extends SubCommand { String suffix = g.getSuffix(); if (prefix != null && !prefix.equals("")) { - group.setPermissionUnchecked(NodeFactory.makePrefixNode(groupWeight, prefix).build()); + group.setPermission(NodeFactory.makePrefixNode(groupWeight, prefix).build()); } if (suffix != null && !suffix.equals("")) { - group.setPermissionUnchecked(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); + group.setPermission(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); } plugin.getStorage().saveGroup(group); @@ -145,26 +145,26 @@ public class MigrationBungeePerms extends SubCommand { // Migrate global perms for (String perm : u.getPerms()) { - user.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).build()); + user.setPermission(MigrationUtils.parseNode(perm, true).build()); } // Migrate per-server perms for (Map.Entry e : u.getServers().entrySet()) { for (String perm : e.getValue().getPerms()) { - user.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).setWorld(e.getKey()).build()); + user.setPermission(MigrationUtils.parseNode(perm, true).setWorld(e.getKey()).build()); } // Migrate per-world perms for (Map.Entry we : e.getValue().getWorlds().entrySet()) { for (String perm : we.getValue().getPerms()) { - user.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).setServer(e.getKey()).setWorld(we.getKey()).build()); + user.setPermission(MigrationUtils.parseNode(perm, true).setServer(e.getKey()).setWorld(we.getKey()).build()); } } } // Migrate groups for (String group : u.getGroupsString()) { - user.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(group))); + user.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(group))); } // Migrate prefix & suffix @@ -172,10 +172,10 @@ public class MigrationBungeePerms extends SubCommand { String suffix = u.getSuffix(); if (prefix != null && !prefix.equals("")) { - user.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); + user.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build()); } if (suffix != null && !suffix.equals("")) { - user.setPermissionUnchecked(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); + user.setPermission(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); } plugin.getStorage().saveUser(user); diff --git a/common/pom.xml b/common/pom.xml index 11f8e7bd0..24e426797 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -38,7 +38,7 @@ io.github.mkremins fanciful - 1.2.0 + 1.2.5 compile diff --git a/common/src/main/java/me/lucko/luckperms/common/api/ApiProvider.java b/common/src/main/java/me/lucko/luckperms/common/api/ApiProvider.java index 0746445ae..852fa5e4d 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/ApiProvider.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/ApiProvider.java @@ -42,7 +42,6 @@ import me.lucko.luckperms.api.context.ContextCalculator; import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.common.api.delegates.NodeFactoryDelegate; import me.lucko.luckperms.common.api.delegates.UserDelegate; -import me.lucko.luckperms.common.core.NodeBuilder; import me.lucko.luckperms.common.core.UserIdentifier; import me.lucko.luckperms.common.event.EventFactory; import me.lucko.luckperms.common.event.LuckPermsEventBus; @@ -153,8 +152,7 @@ public class ApiProvider implements LuckPermsApi { @Override public void cleanupUser(@NonNull User user) { - ApiUtils.checkUser(user); - plugin.getUserManager().cleanup(((UserDelegate) user).getMaster()); + plugin.getUserManager().cleanup(UserDelegate.cast(user)); } @Override @@ -206,7 +204,7 @@ public class ApiProvider implements LuckPermsApi { @Override public Node.Builder buildNode(@NonNull String permission) throws IllegalArgumentException { - return new NodeBuilder(permission); + return me.lucko.luckperms.common.core.NodeFactory.newBuilder(permission); } @SuppressWarnings("unchecked") @@ -217,8 +215,7 @@ public class ApiProvider implements LuckPermsApi { @Override public Optional getContextForUser(User user) { - ApiUtils.checkUser(user); - return Optional.ofNullable(plugin.getContextForUser(((UserDelegate) user).getMaster())); + return Optional.ofNullable(plugin.getContextForUser(UserDelegate.cast(user))); } @SuppressWarnings("unchecked") diff --git a/common/src/main/java/me/lucko/luckperms/common/api/ApiUtils.java b/common/src/main/java/me/lucko/luckperms/common/api/ApiUtils.java index 7899824ac..b1068f883 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/ApiUtils.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/ApiUtils.java @@ -26,29 +26,11 @@ import lombok.experimental.UtilityClass; import com.google.common.base.Preconditions; -import me.lucko.luckperms.api.Group; -import me.lucko.luckperms.api.Track; -import me.lucko.luckperms.api.User; -import me.lucko.luckperms.common.api.delegates.GroupDelegate; -import me.lucko.luckperms.common.api.delegates.TrackDelegate; -import me.lucko.luckperms.common.api.delegates.UserDelegate; import me.lucko.luckperms.common.utils.ArgumentChecker; @UtilityClass public class ApiUtils { - public static void checkUser(User user) { - Preconditions.checkState(user instanceof UserDelegate, "User instance cannot be handled by this implementation."); - } - - public static void checkGroup(Group group) { - Preconditions.checkState(group instanceof GroupDelegate, "Group instance cannot be handled by this implementation."); - } - - public static void checkTrack(Track track) { - Preconditions.checkState(track instanceof TrackDelegate, "Track instance cannot be handled by this implementation."); - } - public static String checkUsername(String s) { Preconditions.checkArgument( !ArgumentChecker.checkUsername(s), diff --git a/common/src/main/java/me/lucko/luckperms/common/api/delegates/GroupDelegate.java b/common/src/main/java/me/lucko/luckperms/common/api/delegates/GroupDelegate.java index 9a26f2978..880fee719 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/delegates/GroupDelegate.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/delegates/GroupDelegate.java @@ -26,147 +26,152 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; +import com.google.common.base.Preconditions; + import me.lucko.luckperms.api.Group; +import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.OptionalInt; +import java.util.stream.Collectors; -import static me.lucko.luckperms.common.api.ApiUtils.checkGroup; import static me.lucko.luckperms.common.api.ApiUtils.checkTime; /** * Provides a link between {@link Group} and {@link me.lucko.luckperms.common.core.model.Group} */ public final class GroupDelegate extends PermissionHolderDelegate implements Group { + public static me.lucko.luckperms.common.core.model.Group cast(Group g) { + Preconditions.checkState(g instanceof GroupDelegate, "Illegal instance " + g.getClass() + " cannot be handled by this implementation."); + return ((GroupDelegate) g).getHandle(); + } @Getter(AccessLevel.PACKAGE) - private final me.lucko.luckperms.common.core.model.Group master; + private final me.lucko.luckperms.common.core.model.Group handle; - public GroupDelegate(@NonNull me.lucko.luckperms.common.core.model.Group master) { - super(master); - this.master = master; + public GroupDelegate(@NonNull me.lucko.luckperms.common.core.model.Group handle) { + super(handle); + this.handle = handle; } @Override public String getName() { - return master.getName(); + return handle.getName(); } @Override public boolean inheritsGroup(@NonNull Group group) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster()); + return handle.inheritsGroup(cast(group)); } @Override public boolean inheritsGroup(@NonNull Group group, @NonNull String server) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster(), server); + return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server); } @Override public boolean inheritsGroup(@NonNull Group group, @NonNull String server, @NonNull String world) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster(), server, world); + return handle.inheritsGroup(cast(group), server, world); } @Override public void setInheritGroup(@NonNull Group group) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster()); + handle.setPermission(NodeFactory.make(cast(group))).throwException(); } @Override public void setInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server); + handle.setPermission(NodeFactory.make(cast(group), server)).throwException(); } @Override public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world); + handle.setPermission(NodeFactory.make(cast(group), server, world)).throwException(); } @Override public void setInheritGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), checkTime(expireAt)); + handle.setPermission(NodeFactory.make(cast(group), checkTime(expireAt))).throwException(); } @Override public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, checkTime(expireAt)); + handle.setPermission(NodeFactory.make(cast(group), server, checkTime(expireAt))).throwException(); } @Override public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world, checkTime(expireAt)); + handle.setPermission(NodeFactory.make(cast(group), server, world, checkTime(expireAt))).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster()); + handle.unsetPermission(NodeFactory.make(cast(group))).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), temporary); + handle.unsetPermission(NodeFactory.make(cast(group), temporary)).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server); + handle.unsetPermission(NodeFactory.make(cast(group), server)).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world); + handle.unsetPermission(NodeFactory.make(cast(group), server, world)).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, temporary); + handle.unsetPermission(NodeFactory.make(cast(group), server, temporary)).throwException(); } @Override public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world, temporary); + handle.unsetPermission(NodeFactory.make(cast(group), server, world, temporary)).throwException(); } @Override public void clearNodes() { - master.clearNodes(); + handle.clearNodes(); } @Override public List getGroupNames() { - return master.getGroupNames(); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .map(Node::getGroupName) + .collect(Collectors.toList()); } @Override public List getLocalGroups(@NonNull String server, @NonNull String world) { - return master.getLocalGroups(server, world); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .filter(n -> n.shouldApplyOnWorld(world, false, true)) + .filter(n -> n.shouldApplyOnServer(server, false, true)) + .map(Node::getGroupName) + .collect(Collectors.toList()); } @Override public OptionalInt getWeight() { - return master.getWeight(); + return handle.getWeight(); } @Override public List getLocalGroups(@NonNull String server) { - return master.getLocalGroups(server); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .filter(n -> n.shouldApplyOnServer(server, false, true)) + .map(Node::getGroupName) + .collect(Collectors.toList()); } public boolean equals(Object o) { diff --git a/common/src/main/java/me/lucko/luckperms/common/api/delegates/PermissionHolderDelegate.java b/common/src/main/java/me/lucko/luckperms/common/api/delegates/PermissionHolderDelegate.java index 2e7137407..57e9e3cfb 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/delegates/PermissionHolderDelegate.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/delegates/PermissionHolderDelegate.java @@ -33,6 +33,7 @@ import me.lucko.luckperms.api.LocalizedNode; import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.PermissionHolder; import me.lucko.luckperms.api.Tristate; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.utils.ExtractedContexts; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; @@ -166,82 +167,82 @@ public class PermissionHolderDelegate implements PermissionHolder { @Override public void setPermission(@NonNull Node node) throws ObjectAlreadyHasException { - master.setPermission(node); + master.setPermission(node).throwException(); } @Override public void setTransientPermission(@NonNull Node node) throws ObjectAlreadyHasException { - master.setTransientPermission(node); + master.setTransientPermission(node).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value)); + master.setPermission(NodeFactory.make(node, value)).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value, server)); + master.setPermission(NodeFactory.make(node, value, server)).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value, server, world)); + master.setPermission(NodeFactory.make(node, value, server, world)).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull long expireAt) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value, checkTime(expireAt))); + master.setPermission(NodeFactory.make(node, value, checkTime(expireAt))).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value, server, checkTime(expireAt))); + master.setPermission(NodeFactory.make(node, value, server, checkTime(expireAt))).throwException(); } @Override public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { - master.setPermission(NodeFactory.make(node, value, server, world, checkTime(expireAt))); + master.setPermission(NodeFactory.make(node, value, server, world, checkTime(expireAt))).throwException(); } @Override public void unsetPermission(@NonNull Node node) throws ObjectLacksException { - master.unsetPermission(node); + master.unsetPermission(node).throwException(); } @Override public void unsetTransientPermission(@NonNull Node node) throws ObjectLacksException { - master.unsetTransientPermission(node); + master.unsetTransientPermission(node).throwException(); } @Override public void unsetPermission(@NonNull String node, @NonNull boolean temporary) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node, temporary)); + master.unsetPermission(NodeFactory.make(node, temporary)).throwException(); } @Override public void unsetPermission(@NonNull String node) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node)); + master.unsetPermission(NodeFactory.make(node)).throwException(); } @Override public void unsetPermission(@NonNull String node, @NonNull String server) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node, server)); + master.unsetPermission(NodeFactory.make(node, server)).throwException(); } @Override public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull String world) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node, server, world)); + master.unsetPermission(NodeFactory.make(node, server, world)).throwException(); } @Override public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node, server, temporary)); + master.unsetPermission(NodeFactory.make(node, server, temporary)).throwException(); } @Override public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { - master.unsetPermission(NodeFactory.make(node, server, world, temporary)); + master.unsetPermission(NodeFactory.make(node, server, world, temporary)).throwException(); } @Override @@ -251,12 +252,25 @@ public class PermissionHolderDelegate implements PermissionHolder { @Override public void clearNodes(String server) { - master.clearNodes(server); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + + master.clearNodes(set); } @Override public void clearNodes(String server, String world) { - master.clearNodes(server, world); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + if (world != null) { + set.add("world", world); + } + + master.clearNodes(set); } @Override @@ -266,12 +280,25 @@ public class PermissionHolderDelegate implements PermissionHolder { @Override public void clearParents(String server) { - master.clearParents(server, true); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + + master.clearParents(set, true); } @Override public void clearParents(String server, String world) { - master.clearParents(server, world, true); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + if (world != null) { + set.add("world", world); + } + + master.clearParents(set, true); } @Override @@ -281,17 +308,38 @@ public class PermissionHolderDelegate implements PermissionHolder { @Override public void clearMeta(String server) { - master.clearMeta(server); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + + master.clearMeta(set); } @Override public void clearMeta(String server, String world) { - master.clearMeta(server, world); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + if (world != null) { + set.add("world", world); + } + + master.clearMeta(set); } @Override public void clearMetaKeys(String key, String server, String world, boolean temporary) { - master.clearMetaKeys(key, server, world, temporary); + MutableContextSet set = new MutableContextSet(); + if (server != null) { + set.add("server", server); + } + if (world != null) { + set.add("world", world); + } + + master.clearMetaKeys(key, set, temporary); } @Override diff --git a/common/src/main/java/me/lucko/luckperms/common/api/delegates/StorageDelegate.java b/common/src/main/java/me/lucko/luckperms/common/api/delegates/StorageDelegate.java index bb5c0006b..93fe00bc4 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/delegates/StorageDelegate.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/delegates/StorageDelegate.java @@ -43,10 +43,7 @@ import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; -import static me.lucko.luckperms.common.api.ApiUtils.checkGroup; import static me.lucko.luckperms.common.api.ApiUtils.checkName; -import static me.lucko.luckperms.common.api.ApiUtils.checkTrack; -import static me.lucko.luckperms.common.api.ApiUtils.checkUser; import static me.lucko.luckperms.common.api.ApiUtils.checkUsername; /** @@ -94,8 +91,7 @@ public class StorageDelegate implements Storage { @Override public CompletableFuture saveUser(User user) { - checkUser(user); - return master.force().saveUser(((UserDelegate) user).getMaster()); + return master.force().saveUser(UserDelegate.cast(user)); } @Override @@ -130,17 +126,15 @@ public class StorageDelegate implements Storage { @Override public CompletableFuture saveGroup(Group group) { - checkGroup(group); - return master.force().saveGroup(((GroupDelegate) group).getMaster()); + return master.force().saveGroup(GroupDelegate.cast(group)); } @Override public CompletableFuture deleteGroup(Group group) { - checkGroup(group); if (group.getName().equalsIgnoreCase(plugin.getConfiguration().get(ConfigKeys.DEFAULT_GROUP_NAME))) { throw new IllegalArgumentException("Cannot delete the default group."); } - return master.force().deleteGroup(((GroupDelegate) group).getMaster(), DeletionCause.API); + return master.force().deleteGroup(GroupDelegate.cast(group), DeletionCause.API); } @Override @@ -165,14 +159,12 @@ public class StorageDelegate implements Storage { @Override public CompletableFuture saveTrack(Track track) { - checkTrack(track); - return master.force().saveTrack(((TrackDelegate) track).getMaster()); + return master.force().saveTrack(TrackDelegate.cast(track)); } @Override public CompletableFuture deleteTrack(Track track) { - checkTrack(track); - return master.force().deleteTrack(((TrackDelegate) track).getMaster(), DeletionCause.API); + return master.force().deleteTrack(TrackDelegate.cast(track), DeletionCause.API); } @Override diff --git a/common/src/main/java/me/lucko/luckperms/common/api/delegates/TrackDelegate.java b/common/src/main/java/me/lucko/luckperms/common/api/delegates/TrackDelegate.java index a4aa598e4..47d5d3378 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/delegates/TrackDelegate.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/delegates/TrackDelegate.java @@ -27,6 +27,8 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; +import com.google.common.base.Preconditions; + import me.lucko.luckperms.api.Group; import me.lucko.luckperms.api.Track; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; @@ -34,81 +36,77 @@ import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; -import static me.lucko.luckperms.common.api.ApiUtils.checkGroup; - /** * Provides a link between {@link Track} and {@link me.lucko.luckperms.common.core.model.Track} */ @AllArgsConstructor public final class TrackDelegate implements Track { + public static me.lucko.luckperms.common.core.model.Track cast(Track g) { + Preconditions.checkState(g instanceof TrackDelegate, "Illegal instance " + g.getClass() + " cannot be handled by this implementation."); + return ((TrackDelegate) g).getHandle(); + } @Getter(AccessLevel.PACKAGE) - private final me.lucko.luckperms.common.core.model.Track master; + private final me.lucko.luckperms.common.core.model.Track handle; @Override public String getName() { - return master.getName(); + return handle.getName(); } @Override public List getGroups() { - return master.getGroups(); + return handle.getGroups(); } @Override public int getSize() { - return master.getSize(); + return handle.getSize(); } @Override public String getNext(@NonNull Group current) throws ObjectLacksException { - checkGroup(current); - return master.getNext(((GroupDelegate) current).getMaster()); + return handle.getNext(GroupDelegate.cast(current)); } @Override public String getPrevious(@NonNull Group current) throws ObjectLacksException { - checkGroup(current); - return master.getPrevious(((GroupDelegate) current).getMaster()); + return handle.getPrevious(GroupDelegate.cast(current)); } @Override public void appendGroup(@NonNull Group group) throws ObjectAlreadyHasException { - checkGroup(group); - master.appendGroup(((GroupDelegate) group).getMaster()); + handle.appendGroup(GroupDelegate.cast(group)); } @Override public void insertGroup(@NonNull Group group, @NonNull int position) throws ObjectAlreadyHasException, IndexOutOfBoundsException { - checkGroup(group); - master.insertGroup(((GroupDelegate) group).getMaster(), position); + handle.insertGroup(GroupDelegate.cast(group), position); } @Override public void removeGroup(@NonNull Group group) throws ObjectLacksException { - checkGroup(group); - master.removeGroup(((GroupDelegate) group).getMaster()); + handle.removeGroup(GroupDelegate.cast(group)); } @Override public void removeGroup(@NonNull String group) throws ObjectLacksException { - master.removeGroup(group); + handle.removeGroup(group); } @Override public boolean containsGroup(@NonNull Group group) { - checkGroup(group); - return master.containsGroup(((GroupDelegate) group).getMaster()); + return handle.containsGroup(GroupDelegate.cast(group)); } @Override public boolean containsGroup(@NonNull String group) { - return master.containsGroup(group); + return handle.containsGroup(group); } @Override public void clearGroups() { - master.clearGroups(); + handle.clearGroups(); } public boolean equals(Object o) { diff --git a/common/src/main/java/me/lucko/luckperms/common/api/delegates/UserDelegate.java b/common/src/main/java/me/lucko/luckperms/common/api/delegates/UserDelegate.java index b76b9777c..75c0c4b4d 100644 --- a/common/src/main/java/me/lucko/luckperms/common/api/delegates/UserDelegate.java +++ b/common/src/main/java/me/lucko/luckperms/common/api/delegates/UserDelegate.java @@ -25,45 +25,53 @@ package me.lucko.luckperms.common.api.delegates; import lombok.Getter; import lombok.NonNull; +import com.google.common.base.Preconditions; + import me.lucko.luckperms.api.Group; +import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.User; import me.lucko.luckperms.api.caching.UserData; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; -import static me.lucko.luckperms.common.api.ApiUtils.checkGroup; import static me.lucko.luckperms.common.api.ApiUtils.checkTime; /** * Provides a link between {@link User} and {@link me.lucko.luckperms.common.core.model.User} */ public final class UserDelegate extends PermissionHolderDelegate implements User { + public static me.lucko.luckperms.common.core.model.User cast(User g) { + Preconditions.checkState(g instanceof UserDelegate, "Illegal instance " + g.getClass() + " cannot be handled by this implementation."); + return ((UserDelegate) g).getHandle(); + } @Getter - private final me.lucko.luckperms.common.core.model.User master; + private final me.lucko.luckperms.common.core.model.User handle; - public UserDelegate(@NonNull me.lucko.luckperms.common.core.model.User master) { - super(master); - this.master = master; + public UserDelegate(@NonNull me.lucko.luckperms.common.core.model.User handle) { + super(handle); + this.handle = handle; } @Override public UUID getUuid() { - return master.getUuid(); + return handle.getUuid(); } @Override public String getName() { - return master.getName(); + return handle.getName(); } @Override public String getPrimaryGroup() { - return master.getPrimaryGroup().getValue(); + return handle.getPrimaryGroup().getValue(); } @Override @@ -76,132 +84,129 @@ public final class UserDelegate extends PermissionHolderDelegate implements User throw new IllegalStateException("User is not a member of that group."); } - master.getPrimaryGroup().setStoredValue(s.toLowerCase()); + handle.getPrimaryGroup().setStoredValue(s.toLowerCase()); } @Override public void refreshPermissions() { - master.getRefreshBuffer().requestDirectly(); + handle.getRefreshBuffer().requestDirectly(); } @Override public Optional getUserDataCache() { - return Optional.ofNullable(master.getUserData()); + return Optional.ofNullable(handle.getUserData()); } @Override public void setupDataCache() { - master.setupData(false); + handle.setupData(false); } @Override public boolean isInGroup(@NonNull Group group) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster()); + return handle.inheritsGroup(GroupDelegate.cast(group)); } @Override public boolean isInGroup(@NonNull Group group, @NonNull String server) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster(), server); + return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server); } @Override public boolean isInGroup(@NonNull Group group, @NonNull String server, @NonNull String world) { - checkGroup(group); - return master.inheritsGroup(((GroupDelegate) group).getMaster(), server, world); + return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server, world); } @Override public void addGroup(@NonNull Group group) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster()); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group))).throwException(); } @Override public void addGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server)).throwException(); } @Override public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, world)).throwException(); } @Override public void addGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), checkTime(expireAt)); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), checkTime(expireAt))).throwException(); } @Override public void addGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, checkTime(expireAt)); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, checkTime(expireAt))).throwException(); } @Override public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { - checkGroup(group); - master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world, checkTime(expireAt)); + handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, world, checkTime(expireAt))).throwException(); } @Override public void removeGroup(@NonNull Group group) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster()); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group))).throwException(); } @Override public void removeGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), temporary); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), temporary)).throwException(); } @Override public void removeGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server)).throwException(); } @Override public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, world)).throwException(); } @Override public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, temporary); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, temporary)).throwException(); } @Override public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { - checkGroup(group); - master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world, temporary); + handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, world, temporary)).throwException(); } @Override public void clearNodes() { - master.clearNodes(); + handle.clearNodes(); } @Override public List getGroupNames() { - return master.getGroupNames(); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .map(Node::getGroupName) + .collect(Collectors.toList()); } @Override public List getLocalGroups(@NonNull String server, @NonNull String world) { - return master.getLocalGroups(server, world); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .filter(n -> n.shouldApplyOnWorld(world, false, true)) + .filter(n -> n.shouldApplyOnServer(server, false, true)) + .map(Node::getGroupName) + .collect(Collectors.toList()); } @Override public List getLocalGroups(@NonNull String server) { - return master.getLocalGroups(server); + return handle.mergePermissionsToList().stream() + .filter(Node::isGroupNode) + .filter(n -> n.shouldApplyOnServer(server, false, true)) + .map(Node::getGroupName) + .collect(Collectors.toList()); } public boolean equals(Object o) { diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/CommandManager.java b/common/src/main/java/me/lucko/luckperms/common/commands/CommandManager.java index 6906b8af6..663e2b6db 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/CommandManager.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/CommandManager.java @@ -117,7 +117,15 @@ public class CommandManager { * @param args the arguments provided */ public Future onCommand(Sender sender, String label, List args) { - return executor.submit(() -> execute(sender, label, args)); + return executor.submit(() -> { + try { + return execute(sender, label, args); + } catch (Exception e) { + plugin.getLog().severe("Exception whilst executing command: " + args.toString()); + e.printStackTrace(); + return null; + } + }); } @SuppressWarnings("unchecked") diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/CommandMeta.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/CommandMeta.java index ea1e8c15e..94f619194 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/CommandMeta.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/CommandMeta.java @@ -36,14 +36,14 @@ public class CommandMeta extends SharedMainCommand DESCRIPTOR = b -> b ? "prefix" : "suffix"; + private final boolean isPrefix; + + public MetaAddChatMeta(boolean isPrefix) { + super("add" + DESCRIPTOR.apply(isPrefix), + "Adds a " + DESCRIPTOR.apply(isPrefix), + isPrefix ? Permission.USER_META_ADDPREFIX : Permission.USER_META_ADDSUFFIX, + isPrefix ? Permission.GROUP_META_ADDPREFIX : Permission.GROUP_META_ADDSUFFIX, + Predicates.inRange(0, 1), Arg.list( - Arg.create("priority", true, "the priority to add the prefix at"), - Arg.create("prefix", true, "the prefix string"), - Arg.create("server", false, "the server to add the prefix on"), - Arg.create("world", false, "the world to add the prefix on") + Arg.create("priority", true, "the priority to add the " + DESCRIPTOR.apply(isPrefix) + " at"), + Arg.create(DESCRIPTOR.apply(isPrefix), true, "the " + DESCRIPTOR.apply(isPrefix) + " string"), + Arg.create("context...", false, "the contexts to add the " + DESCRIPTOR.apply(isPrefix) + " in") ) ); + this.isPrefix = isPrefix; } @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int priority = ArgumentUtils.handlePriority(0, args); - String prefix = ArgumentUtils.handleString(1, args); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); + String meta = ArgumentUtils.handleString(1, args); + MutableContextSet context = ArgumentUtils.handleContext(2, args); - final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); - - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.setPermission(NodeFactory.make(node, true)); - Message.ADDPREFIX_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority); - break; - case SERVER: - holder.setPermission(NodeFactory.make(node, true, server)); - Message.ADDPREFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server); - break; - case SERVER_AND_WORLD: - holder.setPermission(NodeFactory.make(node, true, server, world)); - Message.ADDPREFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server, world); - break; - } + DataMutateResult result = holder.setPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, meta).withExtraContext(context).build()); + if (result.asBoolean()) { + Message.ADD_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), meta, priority, Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) - .action("meta addprefix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) + .action("meta add" + DESCRIPTOR.apply(isPrefix) + " " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { - Message.ALREADY_HAS_PREFIX.send(sender, holder.getFriendlyName()); + } else { + Message.ALREADY_HAS_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix)); return CommandResult.STATE_ERROR; } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempPrefix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempChatMeta.java similarity index 52% rename from common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempPrefix.java rename to common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempChatMeta.java index d2c1d45b8..e393fff07 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempPrefix.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempChatMeta.java @@ -22,85 +22,75 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; -import me.lucko.luckperms.api.MetaUtils; +import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.DataMutateResult; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.TemporaryModifier; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; +import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; -public class MetaAddTempPrefix extends SharedSubCommand { - public MetaAddTempPrefix() { - super("addtempprefix", "Adds a prefix temporarily", Permission.USER_META_ADDTEMP_PREFIX, - Permission.GROUP_META_ADDTEMP_PREFIX, Predicates.notInRange(3, 5), +public class MetaAddTempChatMeta extends SharedSubCommand { + private static final Function DESCRIPTOR = b -> b ? "prefix" : "suffix"; + private final boolean isPrefix; + + public MetaAddTempChatMeta(boolean isPrefix) { + super("addtemp" + DESCRIPTOR.apply(isPrefix), + "Adds a " + DESCRIPTOR.apply(isPrefix) + " temporarily", + isPrefix ? Permission.USER_META_ADDTEMP_PREFIX : Permission.USER_META_ADDTEMP_SUFFIX, + isPrefix ? Permission.GROUP_META_ADDTEMP_PREFIX : Permission.GROUP_META_ADDTEMP_SUFFIX, + Predicates.inRange(0, 2), Arg.list( - Arg.create("priority", true, "the priority to add the prefix at"), - Arg.create("prefix", true, "the prefix string"), - Arg.create("duration", true, "the duration until the prefix expires"), - Arg.create("server", false, "the server to add the prefix on"), - Arg.create("world", false, "the world to add the prefix on") + Arg.create("priority", true, "the priority to add the " + DESCRIPTOR.apply(isPrefix) + " at"), + Arg.create(DESCRIPTOR.apply(isPrefix), true, "the " + DESCRIPTOR.apply(isPrefix) + " string"), + Arg.create("duration", true, "the duration until the " + DESCRIPTOR.apply(isPrefix) + " expires"), + Arg.create("context...", false, "the contexts to add the " + DESCRIPTOR.apply(isPrefix) + " in") ) ); + this.isPrefix = isPrefix; } @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int priority = ArgumentUtils.handlePriority(0, args); - String prefix = ArgumentUtils.handleString(1, args); + String meta = ArgumentUtils.handleString(1, args); long duration = ArgumentUtils.handleDuration(2, args); - String server = ArgumentUtils.handleServer(3, args); - String world = ArgumentUtils.handleWorld(4, args); + MutableContextSet context = ArgumentUtils.handleContext(3, args); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); - final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); + Map.Entry ret = holder.setPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, meta).setExpiry(duration).withExtraContext(context).build(), modifier); - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_PREFIX_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, - DateUtil.formatDateDiff(duration) - ); - break; - case SERVER: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setServer(server).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_PREFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, - server, DateUtil.formatDateDiff(duration) - ); - break; - case SERVER_AND_WORLD: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setServer(server).setWorld(world).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_PREFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, - server, world, DateUtil.formatDateDiff(duration) - ); - break; - } + if (ret.getKey().asBoolean()) { + duration = ret.getValue().getExpiryUnixTime(); + + Message.ADD_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), meta, meta, DateUtil.formatDateDiff(duration), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) - .action("meta addtempprefix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) + .action("meta addtemp" + DESCRIPTOR.apply(isPrefix) + " " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { - Message.ALREADY_HAS_PREFIX.send(sender, holder.getFriendlyName()); + } else { + Message.ALREADY_HAS_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix)); return CommandResult.STATE_ERROR; } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempSuffix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempSuffix.java deleted file mode 100644 index 2128b4080..000000000 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddTempSuffix.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2016 Lucko (Luck) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package me.lucko.luckperms.common.commands.impl.generic.meta; - -import me.lucko.luckperms.api.MetaUtils; -import me.lucko.luckperms.common.commands.Arg; -import me.lucko.luckperms.common.commands.CommandException; -import me.lucko.luckperms.common.commands.CommandResult; -import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; -import me.lucko.luckperms.common.commands.sender.Sender; -import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; -import me.lucko.luckperms.common.config.ConfigKeys; -import me.lucko.luckperms.common.constants.Message; -import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeBuilder; -import me.lucko.luckperms.common.core.TemporaryModifier; -import me.lucko.luckperms.common.core.model.PermissionHolder; -import me.lucko.luckperms.common.data.LogEntry; -import me.lucko.luckperms.common.plugin.LuckPermsPlugin; -import me.lucko.luckperms.common.utils.DateUtil; -import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; - -import java.util.List; -import java.util.stream.Collectors; - -public class MetaAddTempSuffix extends SharedSubCommand { - public MetaAddTempSuffix() { - super("addtempsuffix", "Adds a suffix temporarily", Permission.USER_META_ADDTEMP_SUFFIX, - Permission.GROUP_META_ADDTEMP_SUFFIX, Predicates.notInRange(3, 5), - Arg.list( - Arg.create("priority", true, "the priority to add the suffix at"), - Arg.create("suffix", true, "the suffix string"), - Arg.create("duration", true, "the duration until the suffix expires"), - Arg.create("server", false, "the server to add the suffix on"), - Arg.create("world", false, "the world to add the suffix on") - ) - ); - } - - @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - int priority = ArgumentUtils.handlePriority(0, args); - String suffix = ArgumentUtils.handleString(1, args); - long duration = ArgumentUtils.handleDuration(2, args); - String server = ArgumentUtils.handleServer(3, args); - String world = ArgumentUtils.handleWorld(4, args); - TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); - - final String node = "suffix." + priority + "." + MetaUtils.escapeCharacters(suffix); - - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_SUFFIX_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, - DateUtil.formatDateDiff(duration) - ); - break; - case SERVER: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setServer(server).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_SUFFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, - server, DateUtil.formatDateDiff(duration) - ); - break; - case SERVER_AND_WORLD: - duration = holder.setPermission(new NodeBuilder(node).setValue(true).setServer(server).setWorld(world).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.ADD_TEMP_SUFFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, - server, world, DateUtil.formatDateDiff(duration) - ); - break; - } - - LogEntry.build().actor(sender).acted(holder) - .action("meta addtempsuffix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) - .build().submit(plugin, sender); - - save(holder, sender, plugin); - return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { - Message.ALREADY_HAS_SUFFIX.send(sender, holder.getFriendlyName()); - return CommandResult.STATE_ERROR; - } - } -} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaClear.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaClear.java index 4f37d886d..ab73a42d6 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaClear.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaClear.java @@ -22,13 +22,13 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -41,10 +41,9 @@ import java.util.stream.Collectors; public class MetaClear extends SharedSubCommand { public MetaClear() { - super("clear", "Clears all chat meta", Permission.USER_META_CLEAR, Permission.GROUP_META_CLEAR, Predicates.notInRange(0, 2), + super("clear", "Clears all chat meta", Permission.USER_META_CLEAR, Permission.GROUP_META_CLEAR, Predicates.alwaysFalse(), Arg.list( - Arg.create("server", false, "the server name to filter by"), - Arg.create("world", false, "the world name to filter by") + Arg.create("context...", false, "the contexts to filter by") ) ); } @@ -53,19 +52,12 @@ public class MetaClear extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int before = holder.getNodes().size(); - String server = ArgumentUtils.handleServer(0, args); - String world = ArgumentUtils.handleWorld(1, args); + MutableContextSet context = ArgumentUtils.handleContext(0, args); - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.clearMeta(); - break; - case SERVER: - holder.clearMeta(server); - break; - case SERVER_AND_WORLD: - holder.clearMeta(server, world); - break; + if (context.isEmpty()) { + holder.clearMeta(); + } else { + holder.clearMeta(context); } int changed = before - holder.getNodes().size(); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaInfo.java index 49a831642..843e5b655 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaInfo.java @@ -28,6 +28,7 @@ import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; +import me.lucko.luckperms.common.commands.utils.MetaComparator; import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; @@ -55,8 +56,8 @@ public class MetaInfo extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - SortedSet> prefixes = new TreeSet<>(Util.META_COMPARATOR.reversed()); - SortedSet> suffixes = new TreeSet<>(Util.META_COMPARATOR.reversed()); + SortedSet> prefixes = new TreeSet<>(MetaComparator.INSTANCE.reversed()); + SortedSet> suffixes = new TreeSet<>(MetaComparator.INSTANCE.reversed()); Set meta = new HashSet<>(); // Collect data @@ -81,7 +82,7 @@ public class MetaInfo extends SharedSubCommand { for (Map.Entry e : prefixes) { String location = processLocation(e.getValue(), holder); if (e.getValue().isServerSpecific() || e.getValue().isWorldSpecific() || !e.getValue().getContexts().isEmpty()) { - String context = Util.getNodeContextDescription(e.getValue()); + String context = Util.getAppendableNodeContextString(e.getValue()); Message.CHAT_META_ENTRY_WITH_CONTEXT.send(sender, e.getKey(), e.getValue().getPrefix().getValue(), location, context); } else { Message.CHAT_META_ENTRY.send(sender, e.getKey(), e.getValue().getPrefix().getValue(), location); @@ -96,7 +97,7 @@ public class MetaInfo extends SharedSubCommand { for (Map.Entry e : suffixes) { String location = processLocation(e.getValue(), holder); if (e.getValue().isServerSpecific() || e.getValue().isWorldSpecific() || !e.getValue().getContexts().isEmpty()) { - String context = Util.getNodeContextDescription(e.getValue()); + String context = Util.getAppendableNodeContextString(e.getValue()); Message.CHAT_META_ENTRY_WITH_CONTEXT.send(sender, e.getKey(), e.getValue().getSuffix().getValue(), location, context); } else { Message.CHAT_META_ENTRY.send(sender, e.getKey(), e.getValue().getSuffix().getValue(), location); @@ -111,7 +112,7 @@ public class MetaInfo extends SharedSubCommand { for (LocalizedNode m : meta) { String location = processLocation(m, holder); if (m.isServerSpecific() || m.isWorldSpecific() || !m.getContexts().isEmpty()) { - String context = Util.getNodeContextDescription(m); + String context = Util.getAppendableNodeContextString(m); Message.META_ENTRY_WITH_CONTEXT.send(sender, m.getMeta().getKey(), m.getMeta().getValue(), location, context); } else { Message.META_ENTRY.send(sender, m.getMeta().getKey(), m.getMeta().getValue(), location); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddSuffix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveChatMeta.java similarity index 52% rename from common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddSuffix.java rename to common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveChatMeta.java index 3f2f177ef..8d37b9c41 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaAddSuffix.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveChatMeta.java @@ -22,73 +22,79 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; -import me.lucko.luckperms.api.MetaUtils; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; +import java.util.function.Function; import java.util.stream.Collectors; -public class MetaAddSuffix extends SharedSubCommand { - public MetaAddSuffix() { - super("addsuffix", "Adds a suffix", Permission.USER_META_ADDSUFFIX, Permission.GROUP_META_ADDSUFFIX, - Predicates.notInRange(2, 4), +public class MetaRemoveChatMeta extends SharedSubCommand { + private static final Function DESCRIPTOR = b -> b ? "prefix" : "suffix"; + private final boolean isPrefix; + + public MetaRemoveChatMeta(boolean isPrefix) { + super("remove" + DESCRIPTOR.apply(isPrefix), + "Removes a " + DESCRIPTOR.apply(isPrefix), + isPrefix ? Permission.USER_META_REMOVEPREFIX : Permission.USER_META_REMOVESUFFIX, + isPrefix ? Permission.GROUP_META_REMOVEPREFIX : Permission.GROUP_META_REMOVESUFFIX, + Predicates.is(0), Arg.list( - Arg.create("priority", true, "the priority to add the suffix at"), - Arg.create("suffix", true, "the suffix string"), - Arg.create("server", false, "the server to add the suffix on"), - Arg.create("world", false, "the world to add the suffix on") + Arg.create("priority", true, "the priority to remove the " + DESCRIPTOR.apply(isPrefix) + " at"), + Arg.create(DESCRIPTOR.apply(isPrefix), false, "the " + DESCRIPTOR.apply(isPrefix) + " string"), + Arg.create("server", false, "the server to remove the " + DESCRIPTOR.apply(isPrefix) + " on"), + Arg.create("world", false, "the world to remove the " + DESCRIPTOR.apply(isPrefix) + " on") ) ); + this.isPrefix = isPrefix; } @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int priority = ArgumentUtils.handlePriority(0, args); - String suffix = ArgumentUtils.handleString(1, args); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); + String prefix = ArgumentUtils.handleStringOrElse(1, args, "null"); + MutableContextSet context = ArgumentUtils.handleContext(2, args); - final String node = "suffix." + priority + "." + MetaUtils.escapeCharacters(suffix); + // Handle bulk removal + if (prefix.equalsIgnoreCase("null")) { + holder.removeIf(n -> + n.isPrefix() && + n.getPrefix().getKey() == priority && + !n.isTemporary() && + n.getFullContexts().makeImmutable().equals(context.makeImmutable()) + ); + Message.BULK_REMOVE_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), priority, Util.contextSetToString(context)); + save(holder, sender, plugin); + return CommandResult.SUCCESS; + } - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.setPermission(NodeFactory.make(node, true)); - Message.ADDSUFFIX_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority); - break; - case SERVER: - holder.setPermission(NodeFactory.make(node, true, server)); - Message.ADDSUFFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server); - break; - case SERVER_AND_WORLD: - holder.setPermission(NodeFactory.make(node, true, server, world)); - Message.ADDSUFFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server, world); - break; - } + DataMutateResult result = holder.unsetPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, prefix).withExtraContext(context).build()); + + if (result.asBoolean()) { + Message.REMOVE_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), prefix, priority, Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) - .action("meta addsuffix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) + .action("meta remove" + DESCRIPTOR.apply(isPrefix) + " " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { - Message.ALREADY_HAS_SUFFIX.send(sender, holder.getFriendlyName()); + } else { + Message.DOES_NOT_HAVE_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix)); return CommandResult.STATE_ERROR; } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveSuffix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveSuffix.java deleted file mode 100644 index 68a96d410..000000000 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveSuffix.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2016 Lucko (Luck) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package me.lucko.luckperms.common.commands.impl.generic.meta; - -import me.lucko.luckperms.api.MetaUtils; -import me.lucko.luckperms.api.Node; -import me.lucko.luckperms.common.commands.Arg; -import me.lucko.luckperms.common.commands.CommandException; -import me.lucko.luckperms.common.commands.CommandResult; -import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; -import me.lucko.luckperms.common.commands.sender.Sender; -import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; -import me.lucko.luckperms.common.constants.Message; -import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeFactory; -import me.lucko.luckperms.common.core.model.PermissionHolder; -import me.lucko.luckperms.common.data.LogEntry; -import me.lucko.luckperms.common.plugin.LuckPermsPlugin; -import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -public class MetaRemoveSuffix extends SharedSubCommand { - public MetaRemoveSuffix() { - super("removesuffix", "Removes a suffix", Permission.USER_META_REMOVESUFFIX, Permission.GROUP_META_REMOVESUFFIX, - Predicates.notInRange(1, 4), - Arg.list( - Arg.create("priority", true, "the priority to remove the suffix at"), - Arg.create("suffix", false, "the suffix string"), - Arg.create("server", false, "the server to remove the suffix on"), - Arg.create("world", false, "the world to remove the suffix on") - ) - ); - } - - @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - int priority = ArgumentUtils.handlePriority(0, args); - String suffix = ArgumentUtils.handleStringOrElse(1, args, "null"); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); - - // Handle bulk removal - if (suffix.equalsIgnoreCase("null")) { - List toRemove = new ArrayList<>(); - for (Node node : holder.getNodes().values()) { - if (!node.isSuffix()) continue; - if (node.getSuffix().getKey() != priority) continue; - if (node.isTemporary()) continue; - - if (node.getServer().isPresent()) { - if (server == null) continue; - if (!node.getServer().get().equalsIgnoreCase(server)) continue; - } else { - if (server != null) continue; - } - - if (node.getWorld().isPresent()) { - if (world == null) continue; - if (!node.getWorld().get().equalsIgnoreCase(world)) continue; - } else { - if (world != null) continue; - } - - toRemove.add(node); - } - - toRemove.forEach(holder::unsetPermissionUnchecked); - - Message.BULK_CHANGE_SUCCESS.send(sender, toRemove.size()); - save(holder, sender, plugin); - return CommandResult.SUCCESS; - } - - final String node = "suffix." + priority + "." + MetaUtils.escapeCharacters(suffix); - - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node)); - Message.REMOVESUFFIX_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server)); - Message.REMOVESUFFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world)); - Message.REMOVESUFFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server, world); - break; - } - - LogEntry.build().actor(sender).acted(holder) - .action("meta removesuffix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) - .build().submit(plugin, sender); - - save(holder, sender, plugin); - return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { - Message.DOES_NOT_HAVE_SUFFIX.send(sender, holder.getFriendlyName()); - return CommandResult.STATE_ERROR; - } - } -} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemovePrefix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempChatMeta.java similarity index 50% rename from common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemovePrefix.java rename to common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempChatMeta.java index a7e646822..0fb97c7ef 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemovePrefix.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempChatMeta.java @@ -22,107 +22,79 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; -import me.lucko.luckperms.api.MetaUtils; -import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; -import java.util.ArrayList; import java.util.List; +import java.util.function.Function; import java.util.stream.Collectors; -public class MetaRemovePrefix extends SharedSubCommand { - public MetaRemovePrefix() { - super("removeprefix", "Removes a prefix", Permission.USER_META_REMOVEPREFIX, Permission.GROUP_META_REMOVEPREFIX, - Predicates.notInRange(1, 4), +public class MetaRemoveTempChatMeta extends SharedSubCommand { + private static final Function DESCRIPTOR = b -> b ? "prefix" : "suffix"; + private final boolean isPrefix; + + public MetaRemoveTempChatMeta(boolean isPrefix) { + super("removetemp" + DESCRIPTOR.apply(isPrefix), + "Removes a temporary " + DESCRIPTOR.apply(isPrefix), + isPrefix ? Permission.USER_META_REMOVETEMP_PREFIX : Permission.USER_META_REMOVETEMP_SUFFIX, + isPrefix ? Permission.GROUP_META_REMOVETEMP_PREFIX : Permission.GROUP_META_REMOVETEMP_SUFFIX, + Predicates.is(0), Arg.list( - Arg.create("priority", true, "the priority to remove the prefix at"), - Arg.create("prefix", false, "the prefix string"), - Arg.create("server", false, "the server to remove the prefix on"), - Arg.create("world", false, "the world to remove the prefix on") + Arg.create("priority", true, "the priority to remove the " + DESCRIPTOR.apply(isPrefix) + " at"), + Arg.create(DESCRIPTOR.apply(isPrefix), false, "the " + DESCRIPTOR.apply(isPrefix) + " string"), + Arg.create("server", false, "the server to remove the " + DESCRIPTOR.apply(isPrefix) + " on"), + Arg.create("world", false, "the world to remove the " + DESCRIPTOR.apply(isPrefix) + " on") ) ); + this.isPrefix = isPrefix; } @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int priority = ArgumentUtils.handlePriority(0, args); String prefix = ArgumentUtils.handleStringOrElse(1, args, "null"); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); + MutableContextSet context = ArgumentUtils.handleContext(2, args); // Handle bulk removal if (prefix.equalsIgnoreCase("null")) { - List toRemove = new ArrayList<>(); - for (Node node : holder.getNodes().values()) { - if (!node.isPrefix()) continue; - if (node.getPrefix().getKey() != priority) continue; - if (node.isTemporary()) continue; - - if (node.getServer().isPresent()) { - if (server == null) continue; - if (!node.getServer().get().equalsIgnoreCase(server)) continue; - } else { - if (server != null) continue; - } - - if (node.getWorld().isPresent()) { - if (world == null) continue; - if (!node.getWorld().get().equalsIgnoreCase(world)) continue; - } else { - if (world != null) continue; - } - - toRemove.add(node); - } - - toRemove.forEach(holder::unsetPermissionUnchecked); - - Message.BULK_CHANGE_SUCCESS.send(sender, toRemove.size()); + holder.removeIf(n -> + n.isPrefix() && + n.getPrefix().getKey() == priority && + !n.isPermanent() && + n.getFullContexts().makeImmutable().equals(context.makeImmutable()) + ); + Message.BULK_REMOVE_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), priority, Util.contextSetToString(context)); save(holder, sender, plugin); return CommandResult.SUCCESS; } - final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); + DataMutateResult result = holder.unsetPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, prefix).setExpiry(10L).withExtraContext(context).build()); - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node)); - Message.REMOVEPREFIX_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server)); - Message.REMOVEPREFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world)); - Message.REMOVEPREFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server, world); - break; - } + if (result.asBoolean()) { + Message.REMOVE_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), prefix, priority, Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) - .action("meta removeprefix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) + .action("meta removetemp" + DESCRIPTOR.apply(isPrefix) + " " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { - Message.DOES_NOT_HAVE_PREFIX.send(sender, holder.getFriendlyName()); + } else { + Message.DOES_NOT_HAVE_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix)); return CommandResult.STATE_ERROR; } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempPrefix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempPrefix.java deleted file mode 100644 index 1847d0320..000000000 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempPrefix.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2016 Lucko (Luck) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package me.lucko.luckperms.common.commands.impl.generic.meta; - -import me.lucko.luckperms.api.MetaUtils; -import me.lucko.luckperms.api.Node; -import me.lucko.luckperms.common.commands.Arg; -import me.lucko.luckperms.common.commands.CommandException; -import me.lucko.luckperms.common.commands.CommandResult; -import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; -import me.lucko.luckperms.common.commands.sender.Sender; -import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; -import me.lucko.luckperms.common.constants.Message; -import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeFactory; -import me.lucko.luckperms.common.core.model.PermissionHolder; -import me.lucko.luckperms.common.data.LogEntry; -import me.lucko.luckperms.common.plugin.LuckPermsPlugin; -import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -public class MetaRemoveTempPrefix extends SharedSubCommand { - public MetaRemoveTempPrefix() { - super("removetempprefix", "Removes a temporary prefix", Permission.USER_META_REMOVETEMP_PREFIX, Permission.GROUP_META_REMOVETEMP_PREFIX, - Predicates.notInRange(1, 4), - Arg.list( - Arg.create("priority", true, "the priority to remove the prefix at"), - Arg.create("prefix", false, "the prefix string"), - Arg.create("server", false, "the server to remove the prefix on"), - Arg.create("world", false, "the world to remove the prefix on") - ) - ); - } - - @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - int priority = ArgumentUtils.handlePriority(0, args); - String prefix = ArgumentUtils.handleStringOrElse(1, args, "null"); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); - - // Handle bulk removal - if (prefix.equalsIgnoreCase("null")) { - List toRemove = new ArrayList<>(); - for (Node node : holder.getNodes().values()) { - if (!node.isPrefix()) continue; - if (node.getPrefix().getKey() != priority) continue; - if (node.isPermanent()) continue; - - if (node.getServer().isPresent()) { - if (server == null) continue; - if (!node.getServer().get().equalsIgnoreCase(server)) continue; - } else { - if (server != null) continue; - } - - if (node.getWorld().isPresent()) { - if (world == null) continue; - if (!node.getWorld().get().equalsIgnoreCase(world)) continue; - } else { - if (world != null) continue; - } - - toRemove.add(node); - } - - toRemove.forEach(holder::unsetPermissionUnchecked); - - Message.BULK_CHANGE_SUCCESS.send(sender, toRemove.size()); - save(holder, sender, plugin); - return CommandResult.SUCCESS; - } - - final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); - - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node, true, true)); - Message.REMOVE_TEMP_PREFIX_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server, true)); - Message.REMOVE_TEMP_PREFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world, true)); - Message.REMOVE_TEMP_PREFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), prefix, priority, server, world); - break; - } - - LogEntry.build().actor(sender).acted(holder) - .action("meta removetempprefix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) - .build().submit(plugin, sender); - - save(holder, sender, plugin); - return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { - Message.DOES_NOT_HAVE_PREFIX.send(sender, holder.getFriendlyName()); - return CommandResult.STATE_ERROR; - } - } -} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempSuffix.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempSuffix.java deleted file mode 100644 index d3a8b9f44..000000000 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaRemoveTempSuffix.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2016 Lucko (Luck) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package me.lucko.luckperms.common.commands.impl.generic.meta; - -import me.lucko.luckperms.api.MetaUtils; -import me.lucko.luckperms.api.Node; -import me.lucko.luckperms.common.commands.Arg; -import me.lucko.luckperms.common.commands.CommandException; -import me.lucko.luckperms.common.commands.CommandResult; -import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; -import me.lucko.luckperms.common.commands.sender.Sender; -import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; -import me.lucko.luckperms.common.constants.Message; -import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeFactory; -import me.lucko.luckperms.common.core.model.PermissionHolder; -import me.lucko.luckperms.common.data.LogEntry; -import me.lucko.luckperms.common.plugin.LuckPermsPlugin; -import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -public class MetaRemoveTempSuffix extends SharedSubCommand { - public MetaRemoveTempSuffix() { - super("removetempsuffix", "Removes a temporary suffix", Permission.USER_META_REMOVETEMP_SUFFIX, Permission.GROUP_META_REMOVETEMP_SUFFIX, - Predicates.notInRange(1, 4), - Arg.list( - Arg.create("priority", true, "the priority to remove the suffix at"), - Arg.create("suffix", false, "the suffix string"), - Arg.create("server", false, "the server to remove the suffix on"), - Arg.create("world", false, "the world to remove the suffix on") - ) - ); - } - - @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - int priority = ArgumentUtils.handlePriority(0, args); - String suffix = ArgumentUtils.handleStringOrElse(1, args, "null"); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); - - // Handle bulk removal - if (suffix.equalsIgnoreCase("null")) { - List toRemove = new ArrayList<>(); - for (Node node : holder.getNodes().values()) { - if (!node.isSuffix()) continue; - if (node.getSuffix().getKey() != priority) continue; - if (node.isPermanent()) continue; - - if (node.getServer().isPresent()) { - if (server == null) continue; - if (!node.getServer().get().equalsIgnoreCase(server)) continue; - } else { - if (server != null) continue; - } - - if (node.getWorld().isPresent()) { - if (world == null) continue; - if (!node.getWorld().get().equalsIgnoreCase(world)) continue; - } else { - if (world != null) continue; - } - - toRemove.add(node); - } - - toRemove.forEach(holder::unsetPermissionUnchecked); - - Message.BULK_CHANGE_SUCCESS.send(sender, toRemove.size()); - save(holder, sender, plugin); - return CommandResult.SUCCESS; - } - - final String node = "suffix." + priority + "." + MetaUtils.escapeCharacters(suffix); - - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node, true, true)); - Message.REMOVE_TEMP_SUFFIX_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server, true)); - Message.REMOVE_TEMP_SUFFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world, true)); - Message.REMOVE_TEMP_SUFFIX_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server, world); - break; - } - - LogEntry.build().actor(sender).acted(holder) - .action("meta removetempsuffix " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) - .build().submit(plugin, sender); - - save(holder, sender, plugin); - return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { - Message.DOES_NOT_HAVE_SUFFIX.send(sender, holder.getFriendlyName()); - return CommandResult.STATE_ERROR; - } - } -} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSet.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSet.java index 699c2310d..6fac6cb6b 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSet.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSet.java @@ -23,13 +23,14 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.NodeFactory; @@ -37,19 +38,17 @@ import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; import java.util.stream.Collectors; public class MetaSet extends SharedSubCommand { public MetaSet() { - super("set", "Sets a meta value", Permission.USER_META_SET, Permission.GROUP_META_SET, Predicates.notInRange(2, 4), + super("set", "Sets a meta value", Permission.USER_META_SET, Permission.GROUP_META_SET, Predicates.inRange(0, 1), Arg.list( Arg.create("key", true, "the key to set"), Arg.create("value", true, "the value to set"), - Arg.create("server", false, "the server to add the meta pair on"), - Arg.create("world", false, "the world to add the meta pair on") + Arg.create("context...", false, "the contexts to add the meta pair in") ) ); } @@ -58,35 +57,19 @@ public class MetaSet extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String key = args.get(0); String value = args.get(1); + MutableContextSet context = ArgumentUtils.handleContext(2, args); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); - - Node n = NodeFactory.makeMetaNode(key, value).setServer(server).setWorld(world).build(); + Node n = NodeFactory.makeMetaNode(key, value).withExtraContext(context).build(); if (holder.hasPermission(n).asBoolean()) { Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } - holder.clearMetaKeys(key, server, world, false); + holder.clearMetaKeys(key, context, false); + holder.setPermission(n); - try { - holder.setPermission(n); - } catch (ObjectAlreadyHasException ignored) { - } - - switch (ContextHelper.determine(server, world)) { - case NONE: - Message.SET_META_SUCCESS.send(sender, key, value, holder.getFriendlyName()); - break; - case SERVER: - Message.SET_META_SERVER_SUCCESS.send(sender, key, value, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - Message.SET_META_SERVER_WORLD_SUCCESS.send(sender, key, value, holder.getFriendlyName(), server, world); - break; - } + Message.SET_META_SUCCESS.send(sender, key, value, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("meta set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSetTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSetTemp.java index 78a18fff8..8d6fb7e1f 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSetTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaSetTemp.java @@ -23,13 +23,14 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; @@ -40,20 +41,18 @@ import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; import java.util.stream.Collectors; public class MetaSetTemp extends SharedSubCommand { public MetaSetTemp() { - super("settemp", "Sets a meta value temporarily", Permission.USER_META_SETTEMP, Permission.GROUP_META_SETTEMP, Predicates.notInRange(3, 5), + super("settemp", "Sets a meta value temporarily", Permission.USER_META_SETTEMP, Permission.GROUP_META_SETTEMP, Predicates.inRange(0, 2), Arg.list( Arg.create("key", true, "the key to set"), Arg.create("value", true, "the value to set"), Arg.create("duration", true, "the duration until the meta value expires"), - Arg.create("server", false, "the server to add the meta pair on"), - Arg.create("world", false, "the world to add the meta pair on") + Arg.create("context...", false, "the contexts to add the meta pair in") ) ); } @@ -63,34 +62,20 @@ public class MetaSetTemp extends SharedSubCommand { String key = args.get(0); String value = args.get(1); long duration = ArgumentUtils.handleDuration(2, args); - String server = ArgumentUtils.handleServer(3, args); - String world = ArgumentUtils.handleWorld(4, args); + MutableContextSet context = ArgumentUtils.handleContext(2, args); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); - Node n = NodeFactory.makeMetaNode(key, value).setServer(server).setWorld(world).setExpiry(duration).build(); + Node n = NodeFactory.makeMetaNode(key, value).withExtraContext(context).setExpiry(duration).build(); if (holder.hasPermission(n).asBoolean()) { Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } - holder.clearMetaKeys(key, server, world, true); + holder.clearMetaKeys(key, context, true); + duration = holder.setPermission(n, modifier).getValue().getExpiryUnixTime(); - try { - duration = holder.setPermission(n, modifier).getExpiryUnixTime(); - } catch (ObjectAlreadyHasException ignored) {} - - switch (ContextHelper.determine(server, world)) { - case NONE: - Message.SET_META_TEMP_SUCCESS.send(sender, key, value, holder.getFriendlyName(), DateUtil.formatDateDiff(duration)); - break; - case SERVER: - Message.SET_META_TEMP_SERVER_SUCCESS.send(sender, key, value, holder.getFriendlyName(), server, DateUtil.formatDateDiff(duration)); - break; - case SERVER_AND_WORLD: - Message.SET_META_TEMP_SERVER_WORLD_SUCCESS.send(sender, key, value, holder.getFriendlyName(), server, world, DateUtil.formatDateDiff(duration)); - break; - } + Message.SET_META_TEMP_SUCCESS.send(sender, key, value, holder.getFriendlyName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("meta settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnset.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnset.java index 91c8a61cb..4171e79eb 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnset.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnset.java @@ -22,13 +22,14 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -42,11 +43,10 @@ import java.util.stream.Collectors; public class MetaUnset extends SharedSubCommand { public MetaUnset() { super("unset", "Unsets a meta value", Permission.USER_META_UNSET, Permission.GROUP_META_UNSET, - Predicates.notInRange(1, 3), + Predicates.is(0), Arg.list( Arg.create("key", true, "the key to unset"), - Arg.create("server", false, "the server to remove the meta pair on"), - Arg.create("world", false, "the world to remove the meta pair on") + Arg.create("context...", false, "the contexts to remove the meta pair in") ) ); } @@ -54,22 +54,10 @@ public class MetaUnset extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String key = args.get(0); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - holder.clearMetaKeys(key, server, world, false); - - switch (ContextHelper.determine(server, world)) { - case NONE: - Message.UNSET_META_SUCCESS.send(sender, key, holder.getFriendlyName()); - break; - case SERVER: - Message.UNSET_META_SERVER_SUCCESS.send(sender, key, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - Message.UNSET_META_SERVER_WORLD_SUCCESS.send(sender, key, holder.getFriendlyName(), server, world); - break; - } + holder.clearMetaKeys(key, context, false); + Message.UNSET_META_SUCCESS.send(sender, key, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("meta unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnsetTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnsetTemp.java index 188fae4cb..93b194b9f 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnsetTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/meta/MetaUnsetTemp.java @@ -22,13 +22,14 @@ package me.lucko.luckperms.common.commands.impl.generic.meta; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -42,11 +43,10 @@ import java.util.stream.Collectors; public class MetaUnsetTemp extends SharedSubCommand { public MetaUnsetTemp() { super("unsettemp", "Unsets a temporary meta value", Permission.USER_META_UNSETTEMP, Permission.GROUP_META_UNSETTEMP, - Predicates.notInRange(1, 3), + Predicates.is(0), Arg.list( Arg.create("key", true, "the key to unset"), - Arg.create("server", false, "the server to remove the meta pair on"), - Arg.create("world", false, "the world to remove the meta pair on") + Arg.create("context...", false, "the contexts to remove the meta pair in") ) ); } @@ -54,22 +54,10 @@ public class MetaUnsetTemp extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String key = args.get(0); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - holder.clearMetaKeys(key, server, world, true); - - switch (ContextHelper.determine(server, world)) { - case NONE: - Message.UNSET_META_TEMP_SUCCESS.send(sender, key, holder.getFriendlyName()); - break; - case SERVER: - Message.UNSET_META_TEMP_SERVER_SUCCESS.send(sender, key, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - Message.UNSET_META_TEMP_SERVER_WORLD_SUCCESS.send(sender, key, holder.getFriendlyName(), server, world); - break; - } + holder.clearMetaKeys(key, context, true); + Message.UNSET_META_TEMP_SUCCESS.send(sender, key, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("meta unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupClear.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderClear.java similarity index 60% rename from common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupClear.java rename to common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderClear.java index 931c0b74d..05ebaed21 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupClear.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderClear.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Lucko (Luck) + * Copyright (c) 2017 Lucko (Luck) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,18 +20,20 @@ * SOFTWARE. */ -package me.lucko.luckperms.common.commands.impl.group; +package me.lucko.luckperms.common.commands.impl.generic.other; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.Group; +import me.lucko.luckperms.common.core.model.PermissionHolder; +import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; @@ -39,47 +41,45 @@ import me.lucko.luckperms.common.utils.Predicates; import java.util.List; import java.util.stream.Collectors; -public class GroupClear extends SubCommand { - public GroupClear() { - super("clear", "Clears the group's permissions and parent groups", Permission.GROUP_CLEAR, Predicates.notInRange(0, 2), +public class HolderClear extends SubCommand { + public HolderClear(boolean user) { + super("clear", "Removes all permissions, parents and meta", user ? Permission.USER_CLEAR : Permission.GROUP_CLEAR, + Predicates.alwaysFalse(), Arg.list( - Arg.create("server", false, "the server name to filter by"), - Arg.create("world", false, "the world name to filter by") + Arg.create("context...", false, "the contexts to filter by") ) ); } @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) throws CommandException { - int before = group.getNodes().size(); + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, T holder, List args, String label) throws CommandException { + int before = holder.getNodes().size(); - String server = ArgumentUtils.handleServer(0, args); - String world = ArgumentUtils.handleWorld(1, args); + MutableContextSet context = ArgumentUtils.handleContext(0, args); - switch (ContextHelper.determine(server, world)) { - case NONE: - group.clearNodes(); - break; - case SERVER: - group.clearNodes(server); - break; - case SERVER_AND_WORLD: - group.clearNodes(server, world); - break; - } - - int changed = before - group.getNodes().size(); - if (changed == 1) { - Message.CLEAR_SUCCESS_SINGULAR.send(sender, group.getName(), changed); + if (context.isEmpty()) { + holder.clearNodes(); } else { - Message.CLEAR_SUCCESS.send(sender, group.getName(), changed); + holder.clearNodes(context); } - LogEntry.build().actor(sender).acted(group) + int changed = before - holder.getNodes().size(); + if (changed == 1) { + Message.CLEAR_SUCCESS_SINGULAR.send(sender, holder.getFriendlyName(), changed); + } else { + Message.CLEAR_SUCCESS.send(sender, holder.getFriendlyName(), changed); + } + + LogEntry.build().actor(sender).acted(holder) .action("clear " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); - save(group, sender, plugin); + if (holder instanceof User) { + save((User) holder, sender, plugin); + } else if (holder instanceof Group) { + save((Group) holder, sender, plugin); + } + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderShowTracks.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderShowTracks.java index 68f920f98..8b7c530b9 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderShowTracks.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/other/HolderShowTracks.java @@ -67,7 +67,7 @@ public class HolderShowTracks extends SubCommand .append(t.getName()) .append(": ") .append(Util.listToArrowSep(t.getGroups(), name)) - .append(Util.getNodeContextDescription(node)) + .append(Util.getAppendableNodeContextString(node)) .append("\n") ); } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAdd.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAdd.java index 56fed814b..321a3fcc1 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAdd.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAdd.java @@ -22,21 +22,22 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; import java.util.stream.Collectors; @@ -46,11 +47,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup public class ParentAdd extends SharedSubCommand { public ParentAdd() { super("add", "Sets another group for the object to inherit permissions from", Permission.USER_PARENT_ADD, - Permission.GROUP_PARENT_ADD, Predicates.notInRange(1, 3), + Permission.GROUP_PARENT_ADD, Predicates.is(0), Arg.list( Arg.create("group", true, "the group to inherit from"), - Arg.create("server", false, "the server to inherit the group on"), - Arg.create("world", false, "the world to inherit the group on") + Arg.create("context...", false, "the contexts to inherit the group in") ) ); } @@ -58,8 +58,7 @@ public class ParentAdd extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String groupName = ArgumentUtils.handleName(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); if (!plugin.getStorage().loadGroup(groupName).join()) { Message.GROUP_DOES_NOT_EXIST.send(sender); @@ -72,21 +71,10 @@ public class ParentAdd extends SharedSubCommand { return CommandResult.LOADING_ERROR; } - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.setInheritGroup(group); - Message.SET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName()); - break; - case SERVER: - holder.setInheritGroup(group, server); - Message.SET_INHERIT_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), server); - break; - case SERVER_AND_WORLD: - holder.setInheritGroup(group, server, world); - Message.SET_INHERIT_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), server, world); - break; - } + DataMutateResult result = holder.setInheritGroup(group, context); + + if (result.asBoolean()) { + Message.SET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("parent add " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -94,8 +82,7 @@ public class ParentAdd extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { + } else { Message.ALREADY_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAddTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAddTemp.java index dab193074..e480071e0 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAddTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentAddTemp.java @@ -22,17 +22,20 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.DataMutateResult; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.TemporaryModifier; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -40,9 +43,9 @@ import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroupTabComplete; @@ -50,12 +53,11 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup public class ParentAddTemp extends SharedSubCommand { public ParentAddTemp() { super("addtemp", "Sets another group for the object to inherit permissions from temporarily", - Permission.USER_PARENT_ADDTEMP, Permission.GROUP_PARENT_ADDTEMP, Predicates.notInRange(2, 4), + Permission.USER_PARENT_ADDTEMP, Permission.GROUP_PARENT_ADDTEMP, Predicates.inRange(0, 1), Arg.list( Arg.create("group", true, "the group to inherit from"), Arg.create("duration", true, "the duration of the group membership"), - Arg.create("server", false, "the server to add the group on"), - Arg.create("world", false, "the world to add the group on") + Arg.create("context...", false, "the contexts to inherit the group in") ) ); } @@ -64,8 +66,7 @@ public class ParentAddTemp extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String groupName = ArgumentUtils.handleName(0, args); long duration = ArgumentUtils.handleDuration(1, args); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); + MutableContextSet context = ArgumentUtils.handleContext(2, args); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); if (!plugin.getStorage().loadGroup(groupName).join()) { @@ -79,31 +80,16 @@ public class ParentAddTemp extends SharedSubCommand { return CommandResult.INVALID_ARGS; } - try { - if (group.getName().equalsIgnoreCase(holder.getObjectName())) { - throw new ObjectAlreadyHasException(); - } + if (group.getName().equalsIgnoreCase(holder.getObjectName())) { + Message.ALREADY_TEMP_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName()); + return CommandResult.STATE_ERROR; + } - switch (ContextHelper.determine(server, world)) { - case NONE: - duration = holder.setPermission(new NodeBuilder("group." + group.getName()).setValue(true).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), - DateUtil.formatDateDiff(duration) - ); - break; - case SERVER: - duration = holder.setPermission(new NodeBuilder("group." + group.getName()).setValue(true).setServer(server).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), - server, DateUtil.formatDateDiff(duration) - ); - break; - case SERVER_AND_WORLD: - duration = holder.setPermission(new NodeBuilder("group." + group.getName()).setValue(true).setServer(server).setWorld(world).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), - server, world, DateUtil.formatDateDiff(duration) - ); - break; - } + Map.Entry ret = holder.setPermission(NodeFactory.newBuilder("group." + group.getName()).setExpiry(duration).withExtraContext(context).build(), modifier); + + if (ret.getKey().asBoolean()) { + duration = ret.getValue().getExpiryUnixTime(); + Message.SET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("parent addtemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -111,8 +97,7 @@ public class ParentAddTemp extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { + } else { Message.ALREADY_TEMP_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentClear.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentClear.java index 951696d01..6101038cd 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentClear.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentClear.java @@ -22,13 +22,13 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -41,10 +41,9 @@ import java.util.stream.Collectors; public class ParentClear extends SharedSubCommand { public ParentClear() { - super("clear", "Clears all parents", Permission.USER_PARENT_CLEAR, Permission.GROUP_PARENT_CLEAR, Predicates.notInRange(0, 2), + super("clear", "Clears all parents", Permission.USER_PARENT_CLEAR, Permission.GROUP_PARENT_CLEAR, Predicates.alwaysFalse(), Arg.list( - Arg.create("server", false, "the server name to filter by"), - Arg.create("world", false, "the world name to filter by") + Arg.create("context...", false, "the contexts to filter by") ) ); } @@ -53,19 +52,12 @@ public class ParentClear extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { int before = holder.getNodes().size(); - String server = ArgumentUtils.handleServer(0, args); - String world = ArgumentUtils.handleWorld(1, args); + MutableContextSet context = ArgumentUtils.handleContext(0, args); - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.clearParents(true); - break; - case SERVER: - holder.clearParents(server, true); - break; - case SERVER_AND_WORLD: - holder.clearParents(server, world, true); - break; + if (context.isEmpty()) { + holder.clearParents(true); + } else { + holder.clearParents(context, true); } int changed = before - holder.getNodes().size(); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentInfo.java index 324e6382f..8ddec5a0b 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentInfo.java @@ -22,6 +22,8 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.LocalizedNode; +import me.lucko.luckperms.api.Node; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; @@ -31,9 +33,11 @@ import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; +import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; import java.util.List; +import java.util.SortedSet; public class ParentInfo extends SharedSubCommand { public ParentInfo() { @@ -43,8 +47,38 @@ public class ParentInfo extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { - Message.LISTPARENTS.send(sender, holder.getFriendlyName(), Util.permGroupsToString(holder.mergePermissionsToSortedSet())); - Message.LISTPARENTS_TEMP.send(sender, holder.getFriendlyName(), Util.tempGroupsToString(holder.mergePermissionsToSortedSet())); + Message.LISTPARENTS.send(sender, holder.getFriendlyName(), permGroupsToString(holder.mergePermissionsToSortedSet())); + Message.LISTPARENTS_TEMP.send(sender, holder.getFriendlyName(), tempGroupsToString(holder.mergePermissionsToSortedSet())); return CommandResult.SUCCESS; } + + private static String permGroupsToString(SortedSet nodes) { + StringBuilder sb = new StringBuilder(); + for (Node node : nodes) { + if (!node.isGroupNode()) continue; + if (node.isTemporary()) continue; + + sb.append("&3> &f") + .append(node.getGroupName()) + .append(Util.getAppendableNodeContextString(node)) + .append("\n"); + } + return sb.length() == 0 ? "&3None" : sb.toString(); + } + + private static String tempGroupsToString(SortedSet nodes) { + StringBuilder sb = new StringBuilder(); + for (Node node : nodes) { + if (!node.isGroupNode()) continue; + if (!node.isTemporary()) continue; + + sb.append("&3> &f") + .append(node.getGroupName()) + .append(Util.getAppendableNodeContextString(node)) + .append("\n&2- expires in ") + .append(DateUtil.formatDateDiff(node.getExpiryUnixTime())) + .append("\n"); + } + return sb.length() == 0 ? "&3None" : sb.toString(); + } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemove.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemove.java index c49f7d1ab..f04882312 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemove.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemove.java @@ -22,23 +22,24 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.stream.Collectors; @@ -48,11 +49,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup public class ParentRemove extends SharedSubCommand { public ParentRemove() { super("remove", "Removes a previously set inheritance rule", Permission.USER_PARENT_REMOVE, - Permission.GROUP_PARENT_REMOVE, Predicates.notInRange(1, 3), + Permission.GROUP_PARENT_REMOVE, Predicates.is(0), Arg.list( Arg.create("group", true, "the group to remove"), - Arg.create("server", false, "the server to remove the group on"), - Arg.create("world", false, "the world to remove the group on") + Arg.create("context...", false, "the contexts to remove the group in") ) ); } @@ -60,16 +60,12 @@ public class ParentRemove extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String groupName = ArgumentUtils.handleNameWithSpace(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); - - ContextHelper.CommandContext context = ContextHelper.determine(server, world); + MutableContextSet context = ArgumentUtils.handleContext(1, args); if (holder instanceof User) { User user = (User) holder; - boolean shouldPrevent = (context == ContextHelper.CommandContext.NONE || - (context == ContextHelper.CommandContext.SERVER && server.equalsIgnoreCase("global"))) && + boolean shouldPrevent = (context.isEmpty() || context.has("server", "global")) && plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION_METHOD).equals("stored") && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(groupName); @@ -79,21 +75,9 @@ public class ParentRemove extends SharedSubCommand { } } - try { - switch (context) { - case NONE: - holder.unsetPermission(NodeFactory.make("group." + groupName)); - Message.UNSET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make("group." + groupName, server)); - Message.UNSET_INHERIT_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), groupName, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make("group." + groupName, server, world)); - Message.UNSET_INHERIT_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), groupName, server, world); - break; - } + DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder("group." + groupName).withExtraContext(context).build()); + if (result.asBoolean()) { + Message.UNSET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName, Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("parent remove " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -101,8 +85,7 @@ public class ParentRemove extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { + } else { Message.DOES_NOT_INHERIT.send(sender, holder.getFriendlyName(), groupName); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemoveTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemoveTemp.java index 1880ac399..eafb807ac 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemoveTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentRemoveTemp.java @@ -22,21 +22,22 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.stream.Collectors; @@ -46,11 +47,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup public class ParentRemoveTemp extends SharedSubCommand { public ParentRemoveTemp() { super("removetemp", "Removes a previously set temporary inheritance rule", - Permission.USER_PARENT_REMOVETEMP, Permission.GROUP_PARENT_REMOVETEMP, Predicates.notInRange(1, 3), + Permission.USER_PARENT_REMOVETEMP, Permission.GROUP_PARENT_REMOVETEMP, Predicates.is(0), Arg.list( Arg.create("group", true, "the group to remove"), - Arg.create("server", false, "the server to remove the group on"), - Arg.create("world", false, "the world to remove the group on") + Arg.create("context...", false, "the contexts to remove the group in") ) ); } @@ -58,24 +58,12 @@ public class ParentRemoveTemp extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String groupName = ArgumentUtils.handleNameWithSpace(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make("group." + groupName, true, true)); - Message.UNSET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make("group." + groupName, server, true)); - Message.UNSET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), groupName, server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make("group." + groupName, server, world, true)); - Message.UNSET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), groupName, server, world); - break; - } + DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder("group." + groupName).setExpiry(10L).withExtraContext(context).build()); + + if (result.asBoolean()) { + Message.UNSET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName, Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("parent removetemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -83,8 +71,7 @@ public class ParentRemoveTemp extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { + } else { Message.DOES_NOT_TEMP_INHERIT.send(sender, holder.getFriendlyName(), groupName); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentSet.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentSet.java index dee26cf29..881519697 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentSet.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/parent/ParentSet.java @@ -22,13 +22,14 @@ package me.lucko.luckperms.common.commands.impl.generic.parent; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.model.Group; @@ -37,7 +38,6 @@ import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; import java.util.stream.Collectors; @@ -47,11 +47,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroup public class ParentSet extends SharedSubCommand { public ParentSet() { super("set", "Removes all other groups the object inherits already and adds them to the one given", - Permission.USER_PARENT_SET, Permission.GROUP_PARENT_SET, Predicates.notInRange(1, 3), + Permission.USER_PARENT_SET, Permission.GROUP_PARENT_SET, Predicates.is(0), Arg.list( Arg.create("group", true, "the group to set to"), - Arg.create("server", false, "the server to set the group on"), - Arg.create("world", false, "the world to set the group on") + Arg.create("context...", false, "the contexts to set the group in") ) ); } @@ -59,8 +58,7 @@ public class ParentSet extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String groupName = ArgumentUtils.handleName(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); if (!plugin.getStorage().loadGroup(groupName).join()) { Message.GROUP_DOES_NOT_EXIST.send(sender); @@ -73,44 +71,14 @@ public class ParentSet extends SharedSubCommand { return CommandResult.LOADING_ERROR; } - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.clearParents(null, null, false); - - try { - holder.setInheritGroup(group); - } catch (ObjectAlreadyHasException ignored) {} - - if (holder instanceof User) { - ((User) holder).getPrimaryGroup().setStoredValue(group.getName()); - } - - Message.SET_PARENT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName()); - break; - case SERVER: - holder.clearParents(server, null, false); - - try { - holder.setInheritGroup(group, server); - } catch (ObjectAlreadyHasException ignored) {} - - if (server.equalsIgnoreCase("global") && holder instanceof User) { - ((User) holder).getPrimaryGroup().setStoredValue(group.getName()); - } - - Message.SET_PARENT_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), server); - break; - case SERVER_AND_WORLD: - holder.clearParents(server, world, false); - - try { - holder.setInheritGroup(group, server, world); - } catch (ObjectAlreadyHasException ignored) {} - - Message.SET_PARENT_SERVER_WORLD_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), server, world); - break; + holder.clearParents(context, false); + holder.setInheritGroup(group, context); + if (holder instanceof User) { + ((User) holder).getPrimaryGroup().setStoredValue(group.getName()); } + Message.SET_PARENT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), Util.contextSetToString(context)); + LogEntry.build().actor(sender).acted(holder) .action("parent set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .build().submit(plugin, sender); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheck.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheck.java index 5bee3094d..5f329ec49 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheck.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheck.java @@ -22,16 +22,18 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.Tristate; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; import me.lucko.luckperms.common.commands.utils.Util; +import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; @@ -43,11 +45,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi public class PermissionCheck extends SharedSubCommand { public PermissionCheck() { super("check", "Checks to see if the object has a certain permission node", Permission.USER_PERM_CHECK, - Permission.GROUP_PERM_CHECK, Predicates.notInRange(1, 3), + Permission.GROUP_PERM_CHECK, Predicates.is(0), Arg.list( Arg.create("node", true, "the permission node to check for"), - Arg.create("server", false, "the server to check on"), - Arg.create("world", false, "the world to check on") + Arg.create("context...", false, "the contexts to check in") ) ); } @@ -55,21 +56,12 @@ public class PermissionCheck extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String node = ArgumentUtils.handleString(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - switch (ContextHelper.determine(server, world)) { - case NONE: - Util.sendTristate(sender, node, holder.hasPermission(new NodeBuilder(node).build())); - break; - case SERVER: - Util.sendTristate(sender, node, holder.hasPermission(new NodeBuilder(node).setServer(server).build())); - break; - case SERVER_AND_WORLD: - Util.sendTristate(sender, node, holder.hasPermission(new NodeBuilder(node).setServer(server).setWorld(world).build())); - break; - } + Tristate result = holder.hasPermission(NodeFactory.newBuilder(node).withExtraContext(context).build()); + String s = Util.formatTristate(result); + Message.CHECK_PERMISSION.send(sender, holder.getFriendlyName(), node, s, Util.contextSetToString(context)); return CommandResult.SUCCESS; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheckInherits.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheckInherits.java index af38a3743..850cdfc50 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheckInherits.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionCheckInherits.java @@ -22,17 +22,18 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; import me.lucko.luckperms.common.commands.utils.Util; +import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.core.InheritanceInfo; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; @@ -44,11 +45,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi public class PermissionCheckInherits extends SharedSubCommand { public PermissionCheckInherits() { super("checkinherits", "Checks to see if the object inherits a certain permission node", - Permission.USER_PERM_CHECK_INHERITS, Permission.GROUP_PERM_CHECK_INHERITS, Predicates.notInRange(1, 3), + Permission.USER_PERM_CHECK_INHERITS, Permission.GROUP_PERM_CHECK_INHERITS, Predicates.is(0), Arg.list( Arg.create("node", true, "the permission node to check for"), - Arg.create("server", false, "the server to check on"), - Arg.create("world", false, "the world to check on") + Arg.create("context...", false, "the contexts to check in") ) ); } @@ -56,29 +56,17 @@ public class PermissionCheckInherits extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String node = ArgumentUtils.handleString(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - InheritanceInfo result = null; - switch (ContextHelper.determine(server, world)) { - case NONE: - result = holder.inheritsPermissionInfo(new NodeBuilder(node).build()); - break; - case SERVER: - result = holder.inheritsPermissionInfo(new NodeBuilder(node).setServer(server).build()); - break; - case SERVER_AND_WORLD: - result = holder.inheritsPermissionInfo(new NodeBuilder(node).setServer(server).setWorld(world).build()); - break; - } + InheritanceInfo result = holder.inheritsPermissionInfo(NodeFactory.newBuilder(node).withExtraContext(context).build()); String location = result.getLocation().orElse(null); - if (location != null && location.equalsIgnoreCase(holder.getObjectName())) { + if (location == null || location.equalsIgnoreCase(holder.getObjectName())) { location = "self"; } - Util.sendPluginMessage(sender, "&b" + node + ": " + Util.formatTristate(result.getResult()) + - (location != null ? " &7(inherited from &a" + location + "&7)" : "")); + String s = Util.formatTristate(result.getResult()); + Message.CHECK_PERMISSION.send(sender, holder.getFriendlyName(), node, s, Util.contextSetToString(context), location); return CommandResult.SUCCESS; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionInfo.java index afc10db1b..e10c031c7 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionInfo.java @@ -22,6 +22,10 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import com.google.common.collect.Maps; + +import me.lucko.luckperms.api.LocalizedNode; +import me.lucko.luckperms.api.Node; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; @@ -32,34 +36,54 @@ import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Constants; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; +import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; +import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; +import io.github.mkremins.fanciful.ChatColor; import io.github.mkremins.fanciful.FancyMessage; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.SortedSet; public class PermissionInfo extends SharedSubCommand { public PermissionInfo() { super("info", "Lists the permission nodes the object has", Permission.USER_PERM_INFO, - Permission.GROUP_PERM_INFO, Predicates.alwaysFalse(), + Permission.GROUP_PERM_INFO, Predicates.notInRange(0, 2), Arg.list( - Arg.create("page", false, "the page to view") + Arg.create("page", false, "the page to view"), + Arg.create("filter", false, "the string to filter by") ) ); } @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { + String filter = null; + if (args.size() == 1) { + // it might be a filter, if it's a number, then it relates to a page. + try { + Integer.parseInt(args.get(0)); + } catch (NumberFormatException e) { + // it's not a number, so assume it's the filter. + filter = args.get(0); + } + } else if (args.size() == 2) { + filter = args.get(1); + } + if (sender.getUuid().equals(Constants.CONSOLE_UUID)) { Message.LISTNODES.send(sender, holder.getFriendlyName()); - sender.sendMessage(Util.color(Util.permNodesToStringConsole(holder.mergePermissionsToSortedSet()))); + sender.sendMessage(Util.color(permNodesToString(filter, holder.mergePermissionsToSortedSet()))); } else { int page = ArgumentUtils.handleIntOrElse(0, args, 1); - Map.Entry ent = Util.permNodesToMessage(holder.mergePermissionsToSortedSet(), holder, label, page); + Map.Entry ent = permNodesToMessage(filter, holder.mergePermissionsToSortedSet(), holder, label, page); if (ent.getValue() != null) { Message.LISTNODES_WITH_PAGE.send(sender, holder.getFriendlyName(), ent.getValue()); sender.sendMessage(ent.getKey()); @@ -69,7 +93,114 @@ public class PermissionInfo extends SharedSubCommand { } } - Message.LISTNODES_TEMP.send(sender, holder.getFriendlyName(), Util.tempNodesToString(holder.mergePermissionsToSortedSet())); + Message.LISTNODES_TEMP.send(sender, holder.getFriendlyName(), tempNodesToString(filter, holder.mergePermissionsToSortedSet())); return CommandResult.SUCCESS; } + + private static Map.Entry permNodesToMessage(String filter, SortedSet nodes, PermissionHolder holder, String label, int pageNumber) { + List l = new ArrayList<>(); + for (Node node : nodes) { + if (filter != null && !node.getPermission().startsWith(filter)) { + continue; + } + if (node.isTemporary()) { + continue; + } + + l.add(node); + } + + if (l.isEmpty()) { + return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); + } + + int index = pageNumber - 1; + List> pages = Util.divideList(l, 15); + + if (index < 0 || index >= pages.size()) { + pageNumber = 1; + index = 0; + } + + List page = pages.get(index); + + FancyMessage message = new FancyMessage(""); + String title = "&7(showing page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + nodes.size() + "&7 entries"; + if (filter != null) { + title += " - filtered by &f\"" + filter + "\"&7)"; + } else { + title += ")"; + } + + for (Node node : page) { + message.then("> ").color(ChatColor.getByChar('3')).apply(m -> makeFancy(m, holder, label, node)) + .then(Util.color(node.getPermission())).color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')).apply(m -> makeFancy(m, holder, label, node)) + .apply(node, Util::appendNodeContextDescription) + .then("\n"); + } + + return Maps.immutableEntry(message, title); + } + + private static void makeFancy(FancyMessage message, PermissionHolder holder, String label, Node node) { + message.formattedTooltip( + new FancyMessage("> ") + .color(ChatColor.getByChar('3')) + .then(node.getPermission()) + .color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')), + new FancyMessage(" "), + new FancyMessage("Click to remove this node from " + holder.getFriendlyName()).color(ChatColor.getByChar('7')) + ); + + boolean group = !(holder instanceof User); + String command = NodeFactory.nodeAsCommand(node, group ? holder.getObjectName() : holder.getFriendlyName(), group) + .replace("/luckperms", "/" + label) + .replace("permission set", "permission unset") + .replace("parent add", "parent remove") + .replace(" true", "") + .replace(" false", ""); + + message.suggest(command); + } + + private static String permNodesToString(String filter, SortedSet nodes) { + StringBuilder sb = new StringBuilder(); + for (Node node : nodes) { + if (filter != null && !node.getPermission().startsWith(filter)) { + continue; + } + if (node.isTemporary()) { + continue; + } + + sb.append("&3> ") + .append(node.getValue() ? "&a" : "&c") + .append(node.getPermission()) + .append(" ").append("&7(").append(node.getValue()).append("&7)") + .append(Util.getAppendableNodeContextString(node)) + .append("\n"); + } + return sb.length() == 0 ? "&3None" : sb.toString(); + } + + private static String tempNodesToString(String filter, SortedSet nodes) { + StringBuilder sb = new StringBuilder(); + for (Node node : nodes) { + if (filter != null && !node.getPermission().startsWith(filter)) { + continue; + } + if (!node.isTemporary()) { + continue; + } + + sb.append("&3> ") + .append(node.getValue() ? "&a" : "&c") + .append(node.getPermission()) + .append(Util.getAppendableNodeContextString(node)) + .append("\n&2- expires in ") + .append(DateUtil.formatDateDiff(node.getExpiryUnixTime())) + .append("\n"); + } + return sb.length() == 0 ? "&3None" : sb.toString(); + } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSet.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSet.java index 9ba0fe149..10919bc84 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSet.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSet.java @@ -22,21 +22,22 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; import java.util.stream.Collectors; @@ -47,12 +48,11 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi public class PermissionSet extends SharedSubCommand { public PermissionSet() { super("set", "Sets a permission for the object", Permission.USER_PERM_SET, Permission.GROUP_PERM_SET, - Predicates.notInRange(1, 4), + Predicates.is(0), Arg.list( Arg.create("node", true, "the permission node to set"), Arg.create("true|false", false, "the value of the node"), - Arg.create("server", false, "the server to add the permission node on"), - Arg.create("world", false, "the world to add the permission node on") + Arg.create("context...", false, "the contexts to add the permission in") ) ); } @@ -61,25 +61,12 @@ public class PermissionSet extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { boolean b = ArgumentUtils.handleBoolean(1, args); String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args); + MutableContextSet context = ArgumentUtils.handleContext(2, args); - String server = ArgumentUtils.handleServer(2, args); - String world = ArgumentUtils.handleWorld(3, args); + DataMutateResult result = holder.setPermission(NodeFactory.newBuilder(node).setValue(b).withExtraContext(context).build()); - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.setPermission(NodeFactory.make(node, b)); - Message.SETPERMISSION_SUCCESS.send(sender, node, b, holder.getFriendlyName()); - break; - case SERVER: - holder.setPermission(NodeFactory.make(node, b, server)); - Message.SETPERMISSION_SERVER_SUCCESS.send(sender, node, b, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - holder.setPermission(NodeFactory.make(node, b, server, world)); - Message.SETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, b, holder.getFriendlyName(), server, world); - break; - } + if (result.asBoolean()) { + Message.SETPERMISSION_SUCCESS.send(sender, node, b, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("permission set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -87,8 +74,7 @@ public class PermissionSet extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { + } else { Message.ALREADY_HASPERMISSION.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSetTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSetTemp.java index 0d8b98fb9..a8bef4907 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSetTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionSetTemp.java @@ -22,26 +22,29 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.DataMutateResult; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.TemporaryModifier; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getBoolTabComplete; @@ -50,13 +53,12 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi public class PermissionSetTemp extends SharedSubCommand { public PermissionSetTemp() { super("settemp", "Sets a permission for the object temporarily", Permission.USER_PERM_SETTEMP, - Permission.GROUP_PERM_SETTEMP, Predicates.notInRange(2, 5), + Permission.GROUP_PERM_SETTEMP, Predicates.inRange(0, 1), Arg.list( Arg.create("node", true, "the permission node to set"), Arg.create("true|false", false, "the value of the node"), Arg.create("duration", true, "the duration until the permission node expires"), - Arg.create("server", false, "the server to add the permission node on"), - Arg.create("world", false, "the world to add the permission node on") + Arg.create("context...", false, "the contexts to add the permission in") ) ); } @@ -65,35 +67,15 @@ public class PermissionSetTemp extends SharedSubCommand { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { boolean b = ArgumentUtils.handleBoolean(1, args); String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args); - long duration = ArgumentUtils.handleDuration(2, args); - - String server = ArgumentUtils.handleServer(3, args); - String world = ArgumentUtils.handleWorld(4, args); + MutableContextSet context = ArgumentUtils.handleContext(3, args); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); + Map.Entry result = holder.setPermission(NodeFactory.newBuilder(node).setValue(b).withExtraContext(context).setExpiry(duration).build(), modifier); - try { - switch (ContextHelper.determine(server, world)) { - case NONE: - duration = holder.setPermission(new NodeBuilder(node).setValue(b).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, b, holder.getFriendlyName(), - DateUtil.formatDateDiff(duration) - ); - break; - case SERVER: - duration = holder.setPermission(new NodeBuilder(node).setValue(b).setServer(server).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SETPERMISSION_TEMP_SERVER_SUCCESS.send(sender, node, b, holder.getFriendlyName(), server, - DateUtil.formatDateDiff(duration) - ); - break; - case SERVER_AND_WORLD: - duration = holder.setPermission(new NodeBuilder(node).setValue(b).setServer(server).setWorld(world).setExpiry(duration).build(), modifier).getExpiryUnixTime(); - Message.SETPERMISSION_TEMP_SERVER_WORLD_SUCCESS.send(sender, node, b, holder.getFriendlyName(), - server, world, DateUtil.formatDateDiff(duration) - ); - break; - } + if (result.getKey().asBoolean()) { + duration = result.getValue().getExpiryUnixTime(); + Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, b, holder.getFriendlyName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("permission settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -101,8 +83,7 @@ public class PermissionSetTemp extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectAlreadyHasException e) { + } else { Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnset.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnset.java index 770404ffe..9787811cc 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnset.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnset.java @@ -22,21 +22,22 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.stream.Collectors; @@ -44,11 +45,10 @@ import java.util.stream.Collectors; public class PermissionUnset extends SharedSubCommand { public PermissionUnset() { super("unset", "Unsets a permission for the object", Permission.USER_PERM_UNSET, Permission.GROUP_PERM_UNSET, - Predicates.notInRange(1, 3), + Predicates.is(0), Arg.list( Arg.create("node", true, "the permission node to unset"), - Arg.create("server", false, "the server to remove the permission node on"), - Arg.create("world", false, "the world to remove the permission node on") + Arg.create("context...", false, "the contexts to remove the permission in") ) ); } @@ -56,43 +56,19 @@ public class PermissionUnset extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String node = ArgumentUtils.handleString(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - try { + DataMutateResult result; + if (node.startsWith("group.")) { // unset exact - with false value only - if (node.startsWith("group.")) { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermissionExact(NodeFactory.make(node, false)); - Message.UNSETPERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName()); - break; - case SERVER: - holder.unsetPermissionExact(NodeFactory.make(node, false, server)); - Message.UNSETPERMISSION_SERVER_SUCCESS.send(sender, node, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - holder.unsetPermissionExact(NodeFactory.make(node, false, server, world)); - Message.UNSETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, holder.getFriendlyName(), server, world); - break; - } - } else { - // standard unset - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node)); - Message.UNSETPERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName()); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server)); - Message.UNSETPERMISSION_SERVER_SUCCESS.send(sender, node, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world)); - Message.UNSETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, holder.getFriendlyName(), server, world); - break; - } - } + result = holder.unsetPermissionExact(NodeFactory.newBuilder(node).setValue(false).withExtraContext(context).build()); + } else { + // standard unset + result = holder.unsetPermission(NodeFactory.newBuilder(node).withExtraContext(context).build()); + } + + if (result.asBoolean()) { + Message.UNSETPERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("permission unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -100,8 +76,7 @@ public class PermissionUnset extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { + } else { Message.DOES_NOT_HAVEPERMISSION.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnsetTemp.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnsetTemp.java index dcb841ea7..78ba51dc5 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnsetTemp.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/generic/permission/PermissionUnsetTemp.java @@ -22,21 +22,22 @@ package me.lucko.luckperms.common.commands.impl.generic.permission; +import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; +import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.List; import java.util.stream.Collectors; @@ -44,11 +45,10 @@ import java.util.stream.Collectors; public class PermissionUnsetTemp extends SharedSubCommand { public PermissionUnsetTemp() { super("unsettemp", "Unsets a temporary permission for the object", Permission.USER_PERM_UNSETTEMP, - Permission.GROUP_PERM_UNSETTEMP, Predicates.notInRange(1, 3), + Permission.GROUP_PERM_UNSETTEMP, Predicates.is(0), Arg.list( Arg.create("node", true, "the permission node to unset"), - Arg.create("server", false, "the server to remove the permission node on"), - Arg.create("world", false, "the world to remove the permission node on") + Arg.create("context...", false, "the contexts to remove the permission in") ) ); } @@ -56,42 +56,12 @@ public class PermissionUnsetTemp extends SharedSubCommand { @Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List args, String label) throws CommandException { String node = ArgumentUtils.handleString(0, args); - String server = ArgumentUtils.handleServer(1, args); - String world = ArgumentUtils.handleWorld(2, args); + MutableContextSet context = ArgumentUtils.handleContext(1, args); - try { - // unset exact - with false value only - if (node.startsWith("group.")) { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermissionExact(NodeFactory.make(node, false, true)); - Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName()); - break; - case SERVER: - holder.unsetPermissionExact(NodeFactory.make(node, false, server, true)); - Message.UNSET_TEMP_PERMISSION_SERVER_SUCCESS.send(sender, node, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - holder.unsetPermissionExact(NodeFactory.make(node, false, server, world, true)); - Message.UNSET_TEMP_PERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, holder.getFriendlyName(), server, world); - break; - } - } else { - switch (ContextHelper.determine(server, world)) { - case NONE: - holder.unsetPermission(NodeFactory.make(node, true, true)); - Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName()); - break; - case SERVER: - holder.unsetPermission(NodeFactory.make(node, server, true)); - Message.UNSET_TEMP_PERMISSION_SERVER_SUCCESS.send(sender, node, holder.getFriendlyName(), server); - break; - case SERVER_AND_WORLD: - holder.unsetPermission(NodeFactory.make(node, server, world, true)); - Message.UNSET_TEMP_PERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, holder.getFriendlyName(), server, world); - break; - } - } + DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder(node).setExpiry(10L).withExtraContext(context).build()); + + if (result.asBoolean()) { + Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName(), Util.contextSetToString(context)); LogEntry.build().actor(sender).acted(holder) .action("permission unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) @@ -99,8 +69,7 @@ public class PermissionUnsetTemp extends SharedSubCommand { save(holder, sender, plugin); return CommandResult.SUCCESS; - - } catch (ObjectLacksException e) { + } else { Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, holder.getFriendlyName()); return CommandResult.STATE_ERROR; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupBulkChange.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupBulkChange.java index c405112ae..68406f6dd 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupBulkChange.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupBulkChange.java @@ -34,8 +34,6 @@ import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; import java.util.Iterator; @@ -95,19 +93,8 @@ public class GroupBulkChange extends SubCommand { } } - toRemove.forEach(n -> { - try { - group.unsetPermission(n); - } catch (ObjectLacksException ignored) { - } - }); - - toAdd.forEach(n -> { - try { - group.setPermission(n); - } catch (ObjectAlreadyHasException ignored) { - } - }); + toRemove.forEach(group::unsetPermission); + toAdd.forEach(group::setPermission); save(group, sender, plugin); Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size()); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupInfo.java index 621511e4e..80e5fb056 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupInfo.java @@ -70,14 +70,14 @@ public class GroupInfo extends SubCommand { if (!parents.isEmpty()) { Message.INFO_PARENT_HEADER.send(sender); for (Node node : parents) { - Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getNodeContextDescription(node)); + Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getAppendableNodeContextString(node)); } } if (!tempParents.isEmpty()) { Message.INFO_TEMP_PARENT_HEADER.send(sender); for (Node node : tempParents) { - Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getNodeContextDescription(node)); + Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getAppendableNodeContextString(node)); Message.EMPTY.send(sender, "&f- &2- expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime())); } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupMainCommand.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupMainCommand.java index f635bd26d..2d8615928 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupMainCommand.java @@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableList; import me.lucko.luckperms.common.commands.abstraction.Command; import me.lucko.luckperms.common.commands.abstraction.MainCommand; import me.lucko.luckperms.common.commands.impl.generic.meta.CommandMeta; +import me.lucko.luckperms.common.commands.impl.generic.other.HolderClear; import me.lucko.luckperms.common.commands.impl.generic.other.HolderShowTracks; import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent; import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission; @@ -48,7 +49,7 @@ public class GroupMainCommand extends MainCommand { .add(new GroupSetWeight()) .add(new HolderShowTracks<>(false)) .add(new GroupBulkChange()) - .add(new GroupClear()) + .add(new HolderClear<>(false)) .add(new GroupRename()) .add(new GroupClone()) .build() diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupSetWeight.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupSetWeight.java index 8169ed3a2..9830377e9 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupSetWeight.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/group/GroupSetWeight.java @@ -49,7 +49,7 @@ public class GroupSetWeight extends SubCommand { int weight = ArgumentUtils.handlePriority(0, args); group.removeIf(n -> n.getPermission().startsWith("weight.")); - group.setPermissionUnchecked(NodeFactory.newBuilder("weight." + weight).build()); + group.setPermission(NodeFactory.newBuilder("weight." + weight).build()); save(group, sender, plugin); Message.GROUP_SET_WEIGHT.send(sender, weight, group.getDisplayName()); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/migration/MigrationUtils.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/migration/MigrationUtils.java index 2c7ffd25e..2463b0d8c 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/migration/MigrationUtils.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/migration/MigrationUtils.java @@ -45,7 +45,7 @@ public class MigrationUtils { public static void setGroupWeight(Group group, int weight) { group.removeIf(n -> n.getPermission().startsWith("weight.")); - group.setPermissionUnchecked(NodeFactory.make("weight." + weight)); + group.setPermission(NodeFactory.make("weight." + weight)); } public static String standardizeName(String string) { diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/misc/SearchCommand.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/misc/SearchCommand.java index 0f1c4e056..1d2e8a533 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/misc/SearchCommand.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/misc/SearchCommand.java @@ -22,7 +22,10 @@ package me.lucko.luckperms.common.commands.impl.misc; +import com.google.common.collect.Maps; + import me.lucko.luckperms.api.HeldPermission; +import me.lucko.luckperms.api.Node; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; @@ -32,16 +35,22 @@ import me.lucko.luckperms.common.commands.utils.ArgumentUtils; import me.lucko.luckperms.common.commands.utils.Util; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Permission; +import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; +import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.Predicates; +import io.github.mkremins.fanciful.ChatColor; import io.github.mkremins.fanciful.FancyMessage; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Function; +import java.util.stream.Collectors; public class SearchCommand extends SingleCommand { public SearchCommand() { @@ -78,8 +87,8 @@ public class SearchCommand extends SingleCommand { return s; }); - Map.Entry msgUsers = Util.searchUserResultToMessage(matchedUsers, lookupFunc, label, page); - Map.Entry msgGroups = Util.searchGroupResultToMessage(matchedGroups, label, page); + Map.Entry msgUsers = searchUserResultToMessage(matchedUsers, lookupFunc, label, page); + Map.Entry msgGroups = searchGroupResultToMessage(matchedGroups, label, page); if (msgUsers.getValue() != null) { Message.SEARCH_SHOWING_USERS_WITH_PAGE.send(sender, msgUsers.getValue()); @@ -99,4 +108,107 @@ public class SearchCommand extends SingleCommand { return CommandResult.SUCCESS; } + + private static Map.Entry searchUserResultToMessage(List> results, Function uuidLookup, String label, int pageNumber) { + if (results.isEmpty()) { + return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); + } + + List> sorted = new ArrayList<>(results); + sorted.sort(Comparator.comparing(HeldPermission::getHolder)); + + int index = pageNumber - 1; + List>> pages = Util.divideList(sorted, 15); + + if (index < 0 || index >= pages.size()) { + pageNumber = 1; + index = 0; + } + + List> page = pages.get(index); + List>> uuidMappedPage = page.stream() + .map(hp -> Maps.immutableEntry(uuidLookup.apply(hp.getHolder()), hp)) + .collect(Collectors.toList()); + + FancyMessage message = new FancyMessage(""); + String title = "&7(page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + sorted.size() + "&7 entries)"; + + for (Map.Entry> ent : uuidMappedPage) { + message.then("> ").color(ChatColor.getByChar('3')).apply(m -> makeFancy(m, ent.getKey(), false, label, ent.getValue())) + .then(ent.getKey()).color(ChatColor.getByChar('b')).apply(m -> makeFancy(m, ent.getKey(), false, label, ent.getValue())) + .then(" - ").color(ChatColor.getByChar('7')).apply(m -> makeFancy(m, ent.getKey(), false, label, ent.getValue())) + .then("" + ent.getValue().getValue()).color(ent.getValue().getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')).apply(m -> makeFancy(m, ent.getKey(), false, label, ent.getValue())) + .apply(ent.getValue().asNode(), SearchCommand::appendNodeExpiry) + .apply(ent.getValue().asNode(), Util::appendNodeContextDescription) + .then("\n"); + } + + return Maps.immutableEntry(message, title); + } + + private static Map.Entry searchGroupResultToMessage(List> results, String label, int pageNumber) { + if (results.isEmpty()) { + return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); + } + + List> sorted = new ArrayList<>(results); + sorted.sort(Comparator.comparing(HeldPermission::getHolder)); + + int index = pageNumber - 1; + List>> pages = Util.divideList(sorted, 15); + + if (index < 0 || index >= pages.size()) { + pageNumber = 1; + index = 0; + } + + List> page = pages.get(index); + + FancyMessage message = new FancyMessage(""); + String title = "&7(page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + sorted.size() + "&7 entries)"; + + for (HeldPermission ent : page) { + message.then("> ").color(ChatColor.getByChar('3')).apply(m -> makeFancy(m, ent.getHolder(), true, label, ent)) + .then(ent.getHolder()).color(ChatColor.getByChar('b')).apply(m -> makeFancy(m, ent.getHolder(), true, label, ent)) + .then(" - ").color(ChatColor.getByChar('7')).apply(m -> makeFancy(m, ent.getHolder(), true, label, ent)) + .then("" + ent.getValue()).color(ent.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')).apply(m -> makeFancy(m, ent.getHolder(), true, label, ent)) + .apply(ent.asNode(), SearchCommand::appendNodeExpiry) + .apply(ent.asNode(), Util::appendNodeContextDescription) + .then("\n"); + } + + return Maps.immutableEntry(message, title); + } + + private static void appendNodeExpiry(FancyMessage message, Node node) { + if (!node.isTemporary()) { + return; + } + + message.then(" (").color(ChatColor.getByChar('8')) + .then("expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime())).color(ChatColor.getByChar('7')) + .then(")").color(ChatColor.getByChar('8')); + } + + private static void makeFancy(FancyMessage message, String holderName, boolean group, String label, HeldPermission perm) { + Node node = perm.asNode(); + + message = message.formattedTooltip( + new FancyMessage("> ") + .color(ChatColor.getByChar('3')) + .then(node.getPermission()) + .color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')), + new FancyMessage(" "), + new FancyMessage("Click to remove this node from " + holderName).color(ChatColor.getByChar('7')) + ); + + String command = NodeFactory.nodeAsCommand(node, holderName, group) + .replace("/luckperms", "/" + label) + .replace("permission set", "permission unset") + .replace("parent add", "parent remove") + .replace(" true", "") + .replace(" false", ""); + + message.suggest(command); + } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserBulkChange.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserBulkChange.java index 87996ae36..6040a18e3 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserBulkChange.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserBulkChange.java @@ -34,8 +34,6 @@ import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; import java.util.Iterator; @@ -105,19 +103,8 @@ public class UserBulkChange extends SubCommand { } } - toRemove.forEach(n -> { - try { - user.unsetPermission(n); - } catch (ObjectLacksException ignored) { - } - }); - - toAdd.forEach(n -> { - try { - user.setPermission(n); - } catch (ObjectAlreadyHasException ignored) { - } - }); + toRemove.forEach(user::unsetPermission); + toAdd.forEach(user::setPermission); save(user, sender, plugin); Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size()); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserClear.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserClear.java deleted file mode 100644 index b15ab0012..000000000 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserClear.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2016 Lucko (Luck) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package me.lucko.luckperms.common.commands.impl.user; - -import me.lucko.luckperms.common.commands.Arg; -import me.lucko.luckperms.common.commands.CommandException; -import me.lucko.luckperms.common.commands.CommandResult; -import me.lucko.luckperms.common.commands.abstraction.SubCommand; -import me.lucko.luckperms.common.commands.sender.Sender; -import me.lucko.luckperms.common.commands.utils.ArgumentUtils; -import me.lucko.luckperms.common.commands.utils.ContextHelper; -import me.lucko.luckperms.common.constants.Message; -import me.lucko.luckperms.common.constants.Permission; -import me.lucko.luckperms.common.core.model.User; -import me.lucko.luckperms.common.data.LogEntry; -import me.lucko.luckperms.common.plugin.LuckPermsPlugin; -import me.lucko.luckperms.common.utils.Predicates; - -import java.util.List; -import java.util.stream.Collectors; - -public class UserClear extends SubCommand { - public UserClear() { - super("clear", "Clears the user's permissions and groups", Permission.USER_CLEAR, Predicates.notInRange(0, 2), - Arg.list( - Arg.create("server", false, "the server name to filter by"), - Arg.create("world", false, "the world name to filter by") - ) - ); - } - - @Override - public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) throws CommandException { - int before = user.getNodes().size(); - - String server = ArgumentUtils.handleServer(0, args); - String world = ArgumentUtils.handleWorld(1, args); - - switch (ContextHelper.determine(server, world)) { - case NONE: - user.clearNodes(); - break; - case SERVER: - user.clearNodes(server); - break; - case SERVER_AND_WORLD: - user.clearNodes(server, world); - break; - } - - int changed = before - user.getNodes().size(); - if (changed == 1) { - Message.CLEAR_SUCCESS_SINGULAR.send(sender, user.getName(), changed); - } else { - Message.CLEAR_SUCCESS.send(sender, user.getName(), changed); - } - - LogEntry.build().actor(sender).acted(user) - .action("clear " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) - .build().submit(plugin, sender); - - save(user, sender, plugin); - return CommandResult.SUCCESS; - } -} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserDemote.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserDemote.java index bb94f0801..a55247bc4 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserDemote.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserDemote.java @@ -43,7 +43,6 @@ import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.ArgumentChecker; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; @@ -137,9 +136,7 @@ public class UserDemote extends SubCommand { if (previous == null) { - try { - user.unsetPermission(oldNode); - } catch (ObjectLacksException ignored) {} + user.unsetPermission(oldNode); Message.USER_DEMOTE_ENDOFTRACK.send(sender, track.getName(), user.getName(), old); @@ -163,12 +160,8 @@ public class UserDemote extends SubCommand { return CommandResult.LOADING_ERROR; } - try { - user.unsetPermission(oldNode); - } catch (ObjectLacksException ignored) {} - try { - user.setPermission(NodeFactory.newBuilder("group." + previousGroup.getName()).setServer(server).setWorld(world).build()); - } catch (ObjectAlreadyHasException ignored) {} + user.unsetPermission(oldNode); + user.setPermission(NodeFactory.newBuilder("group." + previousGroup.getName()).setServer(server).setWorld(world).build()); if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) { user.getPrimaryGroup().setStoredValue(previousGroup.getName()); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserInfo.java index a2324446d..c2d11541d 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserInfo.java @@ -75,14 +75,14 @@ public class UserInfo extends SubCommand { if (!parents.isEmpty()) { Message.INFO_PARENT_HEADER.send(sender); for (Node node : parents) { - Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getNodeContextDescription(node)); + Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getAppendableNodeContextString(node)); } } if (!tempParents.isEmpty()) { Message.INFO_TEMP_PARENT_HEADER.send(sender); for (Node node : tempParents) { - Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getNodeContextDescription(node)); + Message.EMPTY.send(sender, "&f- &3> &f" + node.getGroupName() + Util.getAppendableNodeContextString(node)); Message.EMPTY.send(sender, "&f- &2- expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime())); } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserMainCommand.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserMainCommand.java index efd6901ac..2c5d149e6 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserMainCommand.java @@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableList; import me.lucko.luckperms.common.commands.abstraction.Command; import me.lucko.luckperms.common.commands.abstraction.MainCommand; import me.lucko.luckperms.common.commands.impl.generic.meta.CommandMeta; +import me.lucko.luckperms.common.commands.impl.generic.other.HolderClear; import me.lucko.luckperms.common.commands.impl.generic.other.HolderShowTracks; import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent; import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission; @@ -53,7 +54,7 @@ public class UserMainCommand extends MainCommand { .add(new UserDemote()) .add(new HolderShowTracks<>(true)) .add(new UserBulkChange()) - .add(new UserClear()) + .add(new HolderClear<>(true)) .build() ); } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserPromote.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserPromote.java index 5bb43065c..7e0bf7aa7 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserPromote.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserPromote.java @@ -43,7 +43,6 @@ import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.ArgumentChecker; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; @@ -124,9 +123,7 @@ public class UserPromote extends SubCommand { return CommandResult.LOADING_ERROR; } - try { - user.setPermission(NodeFactory.newBuilder("group." + first).setServer(server).setWorld(world).build()); - } catch (ObjectAlreadyHasException ignored) {} + user.setPermission(NodeFactory.newBuilder("group." + first).setServer(server).setWorld(world).build()); switch (ContextHelper.determine(server, world)) { case NONE: @@ -180,12 +177,8 @@ public class UserPromote extends SubCommand { return CommandResult.LOADING_ERROR; } - try { - user.unsetPermission(oldNode); - } catch (ObjectLacksException ignored) {} - try { - user.setPermission(NodeFactory.newBuilder("group." + nextGroup.getName()).setServer(server).setWorld(world).build()); - } catch (ObjectAlreadyHasException ignored) {} + user.unsetPermission(oldNode); + user.setPermission(NodeFactory.newBuilder("group." + nextGroup.getName()).setServer(server).setWorld(world).build()); if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) { user.getPrimaryGroup().setStoredValue(nextGroup.getName()); @@ -207,6 +200,7 @@ public class UserPromote extends SubCommand { LogEntry.build().actor(sender).acted(user) .action("promote " + args.stream().collect(Collectors.joining(" "))) .build().submit(plugin, sender); + save(user, sender, plugin); plugin.getApiProvider().getEventFactory().handleUserPromote(user, track, old, nextGroup.getName()); return CommandResult.SUCCESS; diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserSwitchPrimaryGroup.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserSwitchPrimaryGroup.java index e0b2d7c8a..3f0f4ddaa 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserSwitchPrimaryGroup.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/user/UserSwitchPrimaryGroup.java @@ -22,6 +22,7 @@ package me.lucko.luckperms.common.commands.impl.user; +import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandResult; @@ -35,7 +36,6 @@ import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import java.util.List; @@ -66,10 +66,7 @@ public class UserSwitchPrimaryGroup extends SubCommand { if (!user.inheritsGroup(group)) { Message.USER_PRIMARYGROUP_ERROR_NOTMEMBER.send(sender, user.getName(), group.getName()); - try { - user.setInheritGroup(group); - } catch (ObjectAlreadyHasException ignored) { - } + user.setInheritGroup(group, ContextSet.empty()); } user.getPrimaryGroup().setStoredValue(group.getName()); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditGroup.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditGroup.java index ea819c041..12ded1ee2 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditGroup.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditGroup.java @@ -35,8 +35,6 @@ import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; import java.util.Iterator; @@ -135,19 +133,8 @@ public class BulkEditGroup extends SubCommand { } } - toRemove.forEach(n -> { - try { - user.unsetPermission(n); - } catch (ObjectLacksException ignored) { - } - }); - - toAdd.forEach(n -> { - try { - user.setPermission(n); - } catch (ObjectAlreadyHasException ignored) { - } - }); + toRemove.forEach(user::unsetPermission); + toAdd.forEach(user::setPermission); plugin.getStorage().saveUser(user); plugin.getUserManager().cleanup(user); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditPermission.java b/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditPermission.java index d36b3b7ce..f9a34a6e0 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditPermission.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/impl/usersbulkedit/BulkEditPermission.java @@ -35,8 +35,6 @@ import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.utils.Predicates; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.HashSet; import java.util.Iterator; @@ -125,19 +123,8 @@ public class BulkEditPermission extends SubCommand { } } - toRemove.forEach(n -> { - try { - user.unsetPermission(n); - } catch (ObjectLacksException ignored) { - } - }); - - toAdd.forEach(n -> { - try { - user.setPermission(n); - } catch (ObjectAlreadyHasException ignored) { - } - }); + toRemove.forEach(user::unsetPermission); + toAdd.forEach(user::setPermission); plugin.getStorage().saveUser(user); plugin.getUserManager().cleanup(user); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/utils/ArgumentUtils.java b/common/src/main/java/me/lucko/luckperms/common/commands/utils/ArgumentUtils.java index e05333419..3b295d21b 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/utils/ArgumentUtils.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/utils/ArgumentUtils.java @@ -138,10 +138,9 @@ public class ArgumentUtils { public static MutableContextSet handleContext(int fromIndex, List args) { if (args.size() > fromIndex) { - MutableContextSet set = MutableContextSet.create(); - List contexts = args.subList(fromIndex, args.size() - 1); + List contexts = args.subList(fromIndex, args.size()); for (int i = 0; i < contexts.size(); i++) { String pair = contexts.get(i); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/utils/MetaComparator.java b/common/src/main/java/me/lucko/luckperms/common/commands/utils/MetaComparator.java new file mode 100644 index 000000000..f9c7a1d1a --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/common/commands/utils/MetaComparator.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.common.commands.utils; + +import java.util.Comparator; +import java.util.Map; + +public class MetaComparator implements Comparator> { + public static final MetaComparator INSTANCE = new MetaComparator(); + + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + int result = Integer.compare(o1.getKey(), o2.getKey()); + return result != 0 ? result : 1; + } + +} diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/utils/Util.java b/common/src/main/java/me/lucko/luckperms/common/commands/utils/Util.java index 85f9c9732..c73253b8c 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/utils/Util.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/utils/Util.java @@ -26,38 +26,32 @@ import lombok.experimental.UtilityClass; import com.google.common.collect.Maps; -import me.lucko.luckperms.api.HeldPermission; -import me.lucko.luckperms.api.LocalizedNode; import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.Tristate; +import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Patterns; -import me.lucko.luckperms.common.core.NodeFactory; -import me.lucko.luckperms.common.core.model.PermissionHolder; -import me.lucko.luckperms.common.core.model.User; -import me.lucko.luckperms.common.utils.DateUtil; -import io.github.mkremins.fanciful.ChatColor; import io.github.mkremins.fanciful.FancyMessage; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; -import java.util.SortedSet; import java.util.UUID; -import java.util.function.Function; -import java.util.stream.Collectors; @UtilityClass public class Util { - public static final MetaComparator META_COMPARATOR = new MetaComparator(); - + /** + * Sends a message to the sender, formatted with the plugin prefix and color scheme + * + * @param sender the sender to send the message to + * @param message the message content + */ public static void sendPluginMessage(Sender sender, String message) { String prefix = sender.getPlatform().getLocaleManager().getTranslation(Message.PREFIX); if (prefix == null) { @@ -66,6 +60,12 @@ public class Util { sender.sendMessage(color(prefix + message)); } + /** + * Strips outer quote marks from a list of parsed arguments. + * + * @param input the list of arguments to strip quotes from + * @return an ArrayList containing the contents of input without quotes + */ public static List stripQuotes(List input) { input = new ArrayList<>(input); ListIterator iterator = input.listIterator(); @@ -82,15 +82,17 @@ public class Util { return input; } + /** + * Colorizes a message. + * + * @param s the message to colorize + * @return a colored message + */ public static String color(String s) { - return translateAlternateColorCodes('&', s); - } - - public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { - char[] b = textToTranslate.toCharArray(); + char[] b = s.toCharArray(); for (int i = 0; i < b.length - 1; ++i) { - if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { + if (b[i] == '&' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { b[i] = 167; b[i + 1] = Character.toLowerCase(b[i + 1]); } @@ -99,249 +101,16 @@ public class Util { return new String(b); } + /** + * Strips all color from a message + * + * @param s the message to strip color from + * @return the message without color + */ public static String stripColor(String s) { return s == null ? null : Patterns.STRIP_COLOR_PATTERN.matcher(s).replaceAll(""); } - public static String formatBoolean(boolean b) { - return b ? "&atrue" : "&cfalse"; - } - - public static String formatTristate(Tristate t) { - switch (t) { - case TRUE: - return "&atrue"; - case FALSE: - return "&cfalse"; - default: - return "&cundefined"; - } - } - - public static void sendTristate(Sender sender, String node, Tristate t) { - sender.sendMessage(Util.color("&b" + node + ": " + formatTristate(t))); - } - - public static String getNodeContextDescription(Node node) { - StringBuilder sb = new StringBuilder(); - if (node.isServerSpecific()) { - sb.append(" ").append(contextToString("server", node.getServer().get())); - } - if (node.isWorldSpecific()) { - sb.append(" ").append(contextToString("world", node.getWorld().get())); - } - for (Map.Entry c : node.getContexts().toSet()) { - sb.append(" ").append(contextToString(c.getKey(), c.getValue())); - } - - return sb.toString(); - } - - public static FancyMessage appendNodeContextDescription(Node node, FancyMessage message) { - if (node.isServerSpecific()) { - message = message.then(" "); - message = appendContext("server", node.getServer().get(), message); - } - if (node.isWorldSpecific()) { - message = message.then(" "); - message = appendContext("world", node.getWorld().get(), message); - } - for (Map.Entry c : node.getContexts().toSet()) { - message = message.then(" "); - message = appendContext(c.getKey(), c.getValue(), message); - } - - return message; - } - - public static FancyMessage appendNodeExpiry(Node node, FancyMessage message) { - if (node.isTemporary()) { - message = message.then(" (").color(ChatColor.getByChar('8')); - message = message.then("expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime())).color(ChatColor.getByChar('7')); - message = message.then(")").color(ChatColor.getByChar('8')); - } - - return message; - } - - public static String contextToString(String key, String value) { - return "&8(&7" + key + "=&f" + value + "&8)"; - } - - public static FancyMessage appendContext(String key, String value, FancyMessage message) { - return message - .then("(").color(ChatColor.getByChar('8')) - .then(key + "=").color(ChatColor.getByChar('7')) - .then(value).color(ChatColor.getByChar('f')) - .then(")").color(ChatColor.getByChar('8')); - } - - public static String permNodesToStringConsole(SortedSet nodes) { - StringBuilder sb = new StringBuilder(); - for (Node node : nodes) { - if (node.isTemporary()) continue; - - sb.append("&3> ") - .append(node.getValue() ? "&a" : "&c") - .append(node.getPermission()) - .append(" ").append("&7(").append(node.getValue()).append("&7)") - .append(getNodeContextDescription(node)) - .append("\n"); - } - return sb.length() == 0 ? "&3None" : sb.toString(); - } - - private static FancyMessage makeFancy(PermissionHolder holder, String label, Node node, FancyMessage message) { - message = message.formattedTooltip( - new FancyMessage("> ") - .color(ChatColor.getByChar('3')) - .then(node.getPermission()) - .color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')), - new FancyMessage(" "), - new FancyMessage("Click to remove this node from " + holder.getFriendlyName()).color(ChatColor.getByChar('7')) - ); - - boolean group = !(holder instanceof User); - String command = NodeFactory.nodeAsCommand(node, group ? holder.getObjectName() : holder.getFriendlyName(), group) - .replace("/luckperms", "/" + label) - .replace("permission set", "permission unset") - .replace("parent add", "parent remove") - .replace(" true", "") - .replace(" false", ""); - - message = message.suggest(command); - return message; - } - - private static FancyMessage makeFancy(String holderName, boolean group, String label, HeldPermission perm, FancyMessage message) { - Node node = perm.asNode(); - - message = message.formattedTooltip( - new FancyMessage("> ") - .color(ChatColor.getByChar('3')) - .then(node.getPermission()) - .color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')), - new FancyMessage(" "), - new FancyMessage("Click to remove this node from " + holderName).color(ChatColor.getByChar('7')) - ); - - String command = NodeFactory.nodeAsCommand(node, holderName, group) - .replace("/luckperms", "/" + label) - .replace("permission set", "permission unset") - .replace("parent add", "parent remove") - .replace(" true", "") - .replace(" false", ""); - - message = message.suggest(command); - return message; - } - - public static Map.Entry permNodesToMessage(SortedSet nodes, PermissionHolder holder, String label, int pageNumber) { - List l = new ArrayList<>(); - for (Node node : nodes) { - if (!node.isTemporary()) { - l.add(node); - } - } - - if (l.isEmpty()) { - return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); - } - - int index = pageNumber - 1; - List> pages = divideList(l, 15); - - if (index < 0 || index >= pages.size()) { - pageNumber = 1; - index = 0; - } - - List page = pages.get(index); - - FancyMessage message = new FancyMessage(""); - String title = "&7(showing page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + nodes.size() + "&7 entries)"; - - for (Node node : page) { - message = makeFancy(holder, label, node, message.then("> ").color(ChatColor.getByChar('3'))); - message = makeFancy(holder, label, node, message.then(Util.color(node.getPermission())).color(node.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c'))); - message = appendNodeContextDescription(node, message); - message = message.then("\n"); - } - - return Maps.immutableEntry(message, title); - } - - public static Map.Entry searchUserResultToMessage(List> results, Function uuidLookup, String label, int pageNumber) { - if (results.isEmpty()) { - return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); - } - - List> sorted = new ArrayList<>(results); - sorted.sort(Comparator.comparing(HeldPermission::getHolder)); - - int index = pageNumber - 1; - List>> pages = divideList(sorted, 15); - - if (index < 0 || index >= pages.size()) { - pageNumber = 1; - index = 0; - } - - List> page = pages.get(index); - List>> uuidMappedPage = page.stream() - .map(hp -> Maps.immutableEntry(uuidLookup.apply(hp.getHolder()), hp)) - .collect(Collectors.toList()); - - FancyMessage message = new FancyMessage(""); - String title = "&7(page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + sorted.size() + "&7 entries)"; - - for (Map.Entry> ent : uuidMappedPage) { - message = makeFancy(ent.getKey(), false, label, ent.getValue(), message.then("> ").color(ChatColor.getByChar('3'))); - message = makeFancy(ent.getKey(), false, label, ent.getValue(), message.then(ent.getKey()).color(ChatColor.getByChar('b'))); - message = makeFancy(ent.getKey(), false, label, ent.getValue(), message.then(" - ").color(ChatColor.getByChar('7'))); - message = makeFancy(ent.getKey(), false, label, ent.getValue(), message.then("" + ent.getValue().getValue()).color(ent.getValue().getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c'))); - message = appendNodeExpiry(ent.getValue().asNode(), message); - message = appendNodeContextDescription(ent.getValue().asNode(), message); - message = message.then("\n"); - } - - return Maps.immutableEntry(message, title); - } - - public static Map.Entry searchGroupResultToMessage(List> results, String label, int pageNumber) { - if (results.isEmpty()) { - return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null); - } - - List> sorted = new ArrayList<>(results); - sorted.sort(Comparator.comparing(HeldPermission::getHolder)); - - int index = pageNumber - 1; - List>> pages = divideList(sorted, 15); - - if (index < 0 || index >= pages.size()) { - pageNumber = 1; - index = 0; - } - - List> page = pages.get(index); - - FancyMessage message = new FancyMessage(""); - String title = "&7(page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + sorted.size() + "&7 entries)"; - - for (HeldPermission ent : page) { - message = makeFancy(ent.getHolder(), true, label, ent, message.then("> ").color(ChatColor.getByChar('3'))); - message = makeFancy(ent.getHolder(), true, label, ent, message.then(ent.getHolder()).color(ChatColor.getByChar('b'))); - message = makeFancy(ent.getHolder(), true, label, ent, message.then(" - ").color(ChatColor.getByChar('7'))); - message = makeFancy(ent.getHolder(), true, label, ent, message.then("" + ent.getValue()).color(ent.getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c'))); - message = appendNodeExpiry(ent.asNode(), message); - message = appendNodeContextDescription(ent.asNode(), message); - message = message.then("\n"); - } - - return Maps.immutableEntry(message, title); - } - public static List> divideList(Iterable source, int size) { List> lists = new ArrayList<>(); Iterator it = source.iterator(); @@ -355,60 +124,12 @@ public class Util { return lists; } - public static String tempNodesToString(SortedSet nodes) { - StringBuilder sb = new StringBuilder(); - for (Node node : nodes) { - if (!node.isTemporary()) continue; - - sb.append("&3> ") - .append(node.getValue() ? "&a" : "&c") - .append(node.getPermission()) - .append(getNodeContextDescription(node)) - .append("\n&2- expires in ") - .append(DateUtil.formatDateDiff(node.getExpiryUnixTime())) - .append("\n"); - } - return sb.length() == 0 ? "&3None" : sb.toString(); - } - - public static String permGroupsToString(SortedSet nodes) { - StringBuilder sb = new StringBuilder(); - for (Node node : nodes) { - if (!node.isGroupNode()) continue; - if (node.isTemporary()) continue; - - sb.append("&3> &f") - .append(node.getGroupName()) - .append(getNodeContextDescription(node)) - .append("\n"); - } - return sb.length() == 0 ? "&3None" : sb.toString(); - } - - public static String tempGroupsToString(SortedSet nodes) { - StringBuilder sb = new StringBuilder(); - for (Node node : nodes) { - if (!node.isGroupNode()) continue; - if (!node.isTemporary()) continue; - - sb.append("&3> &f") - .append(node.getGroupName()) - .append(getNodeContextDescription(node)) - .append("\n&2- expires in ") - .append(DateUtil.formatDateDiff(node.getExpiryUnixTime())) - .append("\n"); - } - return sb.length() == 0 ? "&3None" : sb.toString(); - } - public static UUID parseUuid(String s) { try { return UUID.fromString(s); } catch (IllegalArgumentException e) { try { - return UUID.fromString(s.replaceAll( - "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", - "$1-$2-$3-$4-$5")); + return UUID.fromString(s.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } catch (IllegalArgumentException e1) { return null; } @@ -416,57 +137,142 @@ public class Util { } public static String toCommaSep(Collection strings) { - if (strings.isEmpty()) return "&bNone"; + if (strings.isEmpty()) { + return "&bNone"; + } StringBuilder sb = new StringBuilder(); strings.forEach(s -> sb.append("&3").append(s).append("&7, ")); return sb.delete(sb.length() - 2, sb.length()).toString(); } - public static String listToArrowSep(List strings, String highlight) { - if (strings.isEmpty()) return "&bNone"; + public static String listToArrowSep(Collection strings, String highlight) { + if (strings.isEmpty()) { + return "&bNone"; + } StringBuilder sb = new StringBuilder(); - for (String s : strings) { - if (s.equalsIgnoreCase(highlight)) { - sb.append("&b").append(s).append("&7 ---> "); - } else { - sb.append("&3").append(s).append("&7 ---> "); - } - } + strings.forEach(s -> sb.append(s.equalsIgnoreCase(highlight) ? "&b" : "&3").append(s).append("&7 ---> ")); return sb.delete(sb.length() - 6, sb.length()).toString(); } - public static String listToArrowSep(List strings, String highlightFirst, String highlightSecond, boolean reversed) { - if (strings.isEmpty()) return "&6None"; + public static String listToArrowSep(Collection strings, String highlightFirst, String highlightSecond, boolean reversed) { + if (strings.isEmpty()) { + return "&6None"; + } StringBuilder sb = new StringBuilder(); for (String s : strings) { if (s.equalsIgnoreCase(highlightFirst)) { - sb.append("&b").append(s).append("&4").append(reversed ? " <--- " : " ---> "); + sb.append("&b").append(s).append("&4"); } else if (s.equalsIgnoreCase(highlightSecond)) { - sb.append("&b").append(s).append("&7").append(reversed ? " <--- " : " ---> "); + sb.append("&b").append(s).append("&7"); } else { - sb.append("&3").append(s).append("&7").append(reversed ? " <--- " : " ---> "); + sb.append("&3").append(s).append("&7"); } + + sb.append(reversed ? " <--- " : " ---> "); } return sb.delete(sb.length() - 6, sb.length()).toString(); } public static String listToArrowSep(List strings) { - if (strings.isEmpty()) return "&6None"; + if (strings.isEmpty()) { + return "&6None"; + } StringBuilder sb = new StringBuilder(); strings.forEach(s -> sb.append("&3").append(s).append("&b ---> ")); return sb.delete(sb.length() - 6, sb.length()).toString(); } - public static class MetaComparator implements Comparator> { + /** + * Formats a boolean to a colored string + * + * @param b the boolean value + * @return a formatted boolean string + */ + public static String formatBoolean(boolean b) { + return b ? "&atrue" : "&cfalse"; + } - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - int result = Integer.compare(o1.getKey(), o2.getKey()); - return result != 0 ? result : 1; + /** + * Formats a tristate to a colored string + * + * @param t the tristate value + * @return a formatted tristate string + */ + public static String formatTristate(Tristate t) { + switch (t) { + case TRUE: + return "&atrue"; + case FALSE: + return "&cfalse"; + default: + return "&cundefined"; } } + + /** + * Produces a string representing a Nodes context, suitable for appending onto another message line. + * + * @param node the node to query context from + * @return a string representing the nodes context, or an empty string if the node applies globally. + */ + public static String getAppendableNodeContextString(Node node) { + StringBuilder sb = new StringBuilder(); + if (node.isServerSpecific()) { + sb.append(" ").append(contextToString("server", node.getServer().get())); + } + if (node.isWorldSpecific()) { + sb.append(" ").append(contextToString("world", node.getWorld().get())); + } + for (Map.Entry c : node.getContexts().toSet()) { + sb.append(" ").append(contextToString(c.getKey(), c.getValue())); + } + + return sb.toString(); + } + + public static void appendNodeContextDescription(FancyMessage message, Node node) { + if (node.isServerSpecific()) { + message.then(" ").apply(Maps.immutableEntry("server", node.getServer().get()), Util::appendContext); + } + if (node.isWorldSpecific()) { + message.then(" ").apply(Maps.immutableEntry("world", node.getWorld().get()), Util::appendContext); + } + for (Map.Entry c : node.getContexts().toSet()) { + message.then(" ").apply(c, Util::appendContext); + } + } + + /** + * Converts a context pair to a formatted string, surrounded by ( ) brackets. + * + * @param key the context key + * @param value the context value + * @return a formatted string + */ + public static String contextToString(String key, String value) { + return Message.CONTEXT_PAIR.asString(null, key, value); + } + + public static void appendContext(FancyMessage message, Map.Entry ent) { + message.addAll(FancyMessage.fromLegacyText(contextToString(ent.getKey(), ent.getValue()))); + } + + public static String contextSetToString(ContextSet set) { + if (set.isEmpty()) { + return Message.CONTEXT_PAIR__GLOBAL_INLINE.asString(null); + } + + StringBuilder sb = new StringBuilder(); + + for (Map.Entry e : set.toSet()) { + sb.append(Message.CONTEXT_PAIR_INLINE.asString(null, e.getKey(), e.getValue())); + sb.append(Message.CONTEXT_PAIR_SEP.asString(null)); + } + + return sb.delete(sb.length() - Message.CONTEXT_PAIR_SEP.asString(null).length(), sb.length()).toString(); + } } diff --git a/common/src/main/java/me/lucko/luckperms/common/constants/Message.java b/common/src/main/java/me/lucko/luckperms/common/constants/Message.java index 9e10a5f6e..cc6260bd9 100644 --- a/common/src/main/java/me/lucko/luckperms/common/constants/Message.java +++ b/common/src/main/java/me/lucko/luckperms/common/constants/Message.java @@ -201,34 +201,24 @@ public enum Message { LIST_TRACKS("&b{0}'s Tracks:" + "\n" + "{1}", true), LIST_TRACKS_EMPTY("{0} is not on any tracks.", true), - SETPERMISSION_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a.", true), - SETPERMISSION_SERVER_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a on server &b{3}&a.", true), - SETPERMISSION_SERVER_WORLD_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a on server &b{3}&a, world &b{4}&a.", true), - SETPERMISSION_TEMP_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a for a duration of &b{3}&a.", true), - SETPERMISSION_TEMP_SERVER_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a on server &b{3}&a for a duration of &b{4}&a.", true), - SETPERMISSION_TEMP_SERVER_WORLD_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a on server &b{3}&a, world &b{4}&a, for a duration of &b{5}&a.", true), - UNSETPERMISSION_SUCCESS("&aUnset &b{0}&a for &b{1}&a.", true), - UNSETPERMISSION_SERVER_SUCCESS("&aUnset &b{0}&a for &b{1}&a on server &b{2}&a.", true), - UNSETPERMISSION_SERVER_WORLD_SUCCESS("&aUnset &b{0}&a for &b{1}&a on server &b{2}&a, world &b{3}&a.", true), - UNSET_TEMP_PERMISSION_SUCCESS("&aUnset temporary permission &b{0}&a for &b{1}&a.", true), - UNSET_TEMP_PERMISSION_SERVER_SUCCESS("&aUnset temporary permission &b{0}&a for &b{1}&a on server &b{2}&a.", true), - UNSET_TEMP_PERMISSION_SERVER_WORLD_SUCCESS("&aUnset temporary permission &b{0}&a for &b{1}&a on server &b{2}&a, world &b{3}&a.", true), + CONTEXT_PAIR_INLINE("&3{0}=&b{1}", false), + CONTEXT_PAIR__GLOBAL_INLINE("&eglobal", false), + CONTEXT_PAIR_END("&a.", false), + CONTEXT_PAIR_SEP("&a, ", false), - SET_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a.", true), - SET_INHERIT_SERVER_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a on server &b{2}&a.", true), - SET_INHERIT_SERVER_WORLD_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a on server &b{2}&a, world &b{3}&a.", true), - SET_PARENT_SUCCESS("&b{0}&a had their existing parent groups cleared, and now only inherits &b{1}&a.", true), - SET_PARENT_SERVER_SUCCESS("&b{0}&a had their existing parent groups cleared, and now only inherits &b{1}&a on server &b{2}&a.", true), - SET_PARENT_SERVER_WORLD_SUCCESS("&b{0}&a had their existing parent groups cleared, and now only inherits &b{1}&a on server &b{2}&a, world &b{3}&a.", true), - SET_TEMP_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a for a duration of &b{2}&a.", true), - SET_TEMP_INHERIT_SERVER_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a on server &b{2}&a for a duration of &b{3}&a.", true), - SET_TEMP_INHERIT_SERVER_WORLD_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a on server &b{2}&a, world &b{3}&a, for a duration of &b{4}&a.", true), - UNSET_INHERIT_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&a.", true), - UNSET_INHERIT_SERVER_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&a on server &b{2}&a.", true), - UNSET_INHERIT_SERVER_WORLD_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&a on server &b{2}&a, world &b{3}&a.", true), - UNSET_TEMP_INHERIT_SUCCESS("&b{0}&a no longer temporarily inherits permissions from &b{1}&a.", true), - UNSET_TEMP_INHERIT_SERVER_SUCCESS("&b{0}&a no longer temporarily inherits permissions from &b{1}&a on server &b{2}&a.", true), - UNSET_TEMP_INHERIT_SERVER_WORLD_SUCCESS("&b{0}&a no longer temporarily inherits permissions from &b{1}&a on server &b{2}&a, world &b{3}&a.", true), + CONTEXT_PAIR("&8(&7{0}=&f{1}&8)", false), + + CHECK_PERMISSION("&b{0}&a has permission &b{1}&a set to {2}&a in context {3}&a.", true), + CHECK_PERMISSION_INHERITED("&b{0}&a has permission &b{1}&a set to {2}&a in context {3}&a, inherited from &b{4}&a.", true), + SETPERMISSION_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a in context {3}&a.", true), + SETPERMISSION_TEMP_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a for a duration of &b{3}&a in context {4}&a.", true), + UNSETPERMISSION_SUCCESS("&aUnset &b{0}&a for &b{1}&a in context {2}&a.", true), + UNSET_TEMP_PERMISSION_SUCCESS("&aUnset temporary permission &b{0}&a for &b{1}&a in context {2}&a.", true), + SET_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a in context {2}&a.", true), + SET_TEMP_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a for a duration of &b{2}&a in context {3}&a.", true), + SET_PARENT_SUCCESS("&b{0}&a had their existing parent groups cleared, and now only inherits &b{1}&a in context {2}&a.", true), + UNSET_INHERIT_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&a in context {2}&a.", true), + UNSET_TEMP_INHERIT_SUCCESS("&b{0}&a no longer temporarily inherits permissions from &b{1}&a in context {2}&a.", true), CLEAR_SUCCESS("&b{0}&a's permissions were cleared. (&b{1}&a nodes were removed.)", true), CLEAR_SUCCESS_SINGULAR("&b{0}&a's permissions were cleared. (&b{1}&a node was removed.)", true), @@ -236,6 +226,7 @@ public enum Message { PARENT_CLEAR_SUCCESS_SINGULAR("&b{0}&a's parents were cleared. (&b{1}&a node was removed.)", true), META_CLEAR_SUCCESS("&b{0}&a's meta was cleared. (&b{1}&a nodes were removed.)", true), META_CLEAR_SUCCESS_SINGULAR("&b{0}&a's meta was cleared. (&b{1}&a node was removed.)", true), + ILLEGAL_DATE_ERROR("Could not parse date '{0}'.", true), PAST_DATE_ERROR("You cannot set a date in the past!", true), @@ -251,54 +242,23 @@ public enum Message { META_NONE("&b{0} has no meta.", true), META_INVALID_PRIORITY("Invalid priority '{0}'. Expected a number.", true), - ALREADY_HAS_PREFIX("{0} already has that prefix set.", true), - ALREADY_HAS_SUFFIX("{0} already has that suffix set.", true), - DOES_NOT_HAVE_PREFIX("{0} doesn't have that prefix set.", true), - DOES_NOT_HAVE_SUFFIX("{0} doesn't have that suffix set.", true), - ADDPREFIX_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a.", true), - ADDPREFIX_SERVER_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a.", true), - ADDPREFIX_SERVER_WORLD_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, world &b{4}&a.", true), - REMOVEPREFIX_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a at priority &b{2}&a removed.", true), - REMOVEPREFIX_SERVER_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a.", true), - REMOVEPREFIX_SERVER_WORLD_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a, world &b{4}&a.", true), + ALREADY_HAS_CHAT_META("{0} already has that {1} set.", true), + DOES_NOT_HAVE_CHAT_META("{0} doesn't have that {1} set.", true), - ADDSUFFIX_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a.", true), - ADDSUFFIX_SERVER_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a.", true), - ADDSUFFIX_SERVER_WORLD_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, world &b{4}&a.", true), - REMOVESUFFIX_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a at priority &b{2}&a removed.", true), - REMOVESUFFIX_SERVER_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a.", true), - REMOVESUFFIX_SERVER_WORLD_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a, world &b{4}&a.", true), - - ADD_TEMP_PREFIX_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a for a duration of &b{3}&a.", true), - ADD_TEMP_PREFIX_SERVER_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, for a duration of &b{4}&a.", true), - ADD_TEMP_PREFIX_SERVER_WORLD_SUCCESS("&b{0}&a had prefix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, world &b{4}&a, for a duration of &b{5}&a.", true), - REMOVE_TEMP_PREFIX_SUCCESS("&b{0}&a had temporary prefix &f\"{1}&f\"&a at priority &b{2}&a removed.", true), - REMOVE_TEMP_PREFIX_SERVER_SUCCESS("&b{0}&a had temporary prefix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a.", true), - REMOVE_TEMP_PREFIX_SERVER_WORLD_SUCCESS("&b{0}&a had temporary prefix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a, world &b{4}&a.", true), - - ADD_TEMP_SUFFIX_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a for a duration of &b{3}&a.", true), - ADD_TEMP_SUFFIX_SERVER_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, for a duration of &b{4}&a.", true), - ADD_TEMP_SUFFIX_SERVER_WORLD_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&a on server &b{3}&a, world &b{4}&a, for a duration of &b{5}&a.", true), - REMOVE_TEMP_SUFFIX_SUCCESS("&b{0}&a had temporary suffix &f\"{1}&f\"&a at priority &b{1}&a removed.", true), - REMOVE_TEMP_SUFFIX_SERVER_SUCCESS("&b{0}&a had temporary suffix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a.", true), - REMOVE_TEMP_SUFFIX_SERVER_WORLD_SUCCESS("&b{0}&a had temporary suffix &f\"{1}&f\"&a at priority &b{2}&a removed on server &b{3}&a, world &b{4}&a.", true), + ADD_CHATMETA_SUCCESS("&b{0}&a had {1} &f\"{2}&f\"&a set at a priority of &b{3}&a in context {4}&a.", true), + ADD_TEMP_CHATMETA_SUCCESS("&b{0}&a had {1} &f\"{2}&f\"&a set at a priority of &b{3}&a for a duration of &b{4}&a in context {5}&a.", true), + REMOVE_CHATMETA_SUCCESS("&b{0}&a had {1} &f\"{2}&f\"&a at priority &b{3}&a removed in context {4}&a.", true), + BULK_REMOVE_CHATMETA_SUCCESS("&b{0}&a had all {1}es at priority &b{3}&a removed in context {4}&a.", true), + REMOVE_TEMP_CHATMETA_SUCCESS("&b{0}&a had temporary {1} &f\"{2}&f\"&a at priority &b{3}&a removed in context {4}&a.", true), + BULK_REMOVE_TEMP_CHATMETA_SUCCESS("&b{0}&a had all temporary {1}es at priority &b{3}&a removed in context {4}&a.", true), ALREADY_HAS_META("{0} already has that meta key value pair set.", true), - SET_META_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a.", true), - SET_META_SERVER_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a on server &b{3}&a.", true), - SET_META_SERVER_WORLD_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a on server &b{3}&a, world &b{4}&a.", true), - SET_META_TEMP_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a for a duration of &b{3}&a.", true), - SET_META_TEMP_SERVER_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a on server &b{3}&a for a duration of &b{4}&a.", true), - SET_META_TEMP_SERVER_WORLD_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a on server &b{3}&a, world &b{4}&a, for a duration of &b{5}&a.", true), - - UNSET_META_SUCCESS("&aUnset meta value with key &f\"{0}&f\"&a for &b{1}&a.", true), - UNSET_META_SERVER_SUCCESS("&aUnset meta value with key &f\"{0}&f\"&a for &b{1}&a on server &b{2}&a.", true), - UNSET_META_SERVER_WORLD_SUCCESS("&aUnset meta value with key &f\"{0}&f\"&a for &b{1}&a on server &b{2}&a, world &b{3}&a.", true), - UNSET_META_TEMP_SUCCESS("&aUnset temporary meta value with key &f\"{0}&f\"&a for &b{1}&a.", true), - UNSET_META_TEMP_SERVER_SUCCESS("&aUnset temporary meta value with key &f\"{0}&f\"&a for &b{1}&a on server &b{2}&a.", true), - UNSET_META_TEMP_SERVER_WORLD_SUCCESS("&aUnset temporary meta value with key &f\"{0}&f\"&a for &b{1}&a on server &b{2}&a, world &b{3}&a.", true), + SET_META_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a in context {3}&a.", true), + SET_META_TEMP_SUCCESS("&aSet meta value for key &f\"{0}&f\"&a to &f\"{1}&f\"&a for &b{2}&a for a duration of &b{3}&a in context {4}&a.", true), + UNSET_META_SUCCESS("&aUnset meta value with key &f\"{0}&f\"&a for &b{1}&a in context {2}&a.", true), + UNSET_META_TEMP_SUCCESS("&aUnset temporary meta value with key &f\"{0}&f\"&a for &b{1}&a in context {2}&a.", true), BULK_CHANGE_TYPE_ERROR("Invalid type. Was expecting 'server' or 'world'.", true), BULK_CHANGE_SUCCESS("&aApplied bulk change successfully. {0} records were changed.", true), @@ -450,42 +410,32 @@ public enum Message { @Override public String toString() { - return Util.color(showPrefix ? PREFIX + message : message); + return asString(null); } - public String asString(LocaleManager localeManager) { - String prefix = localeManager.getTranslation(PREFIX); + public String asString(LocaleManager localeManager, Object... objects) { + String prefix = null; + if (localeManager != null) { + prefix = localeManager.getTranslation(PREFIX); + } if (prefix == null) { prefix = PREFIX.getMessage(); } - String s = localeManager.getTranslation(this); + String s = null; + if (localeManager != null) { + s = localeManager.getTranslation(this); + } if (s == null) { s = message; } - s = s.replace("{PREFIX}", prefix).replace("\\n", "\n"); - return Util.color(showPrefix ? (prefix + s) : (s)); + s = format(s.replace("{PREFIX}", prefix).replace("\\n", "\n"), objects); + return Util.color(showPrefix ? prefix + s : s); } public void send(Sender sender, Object... objects) { - String prefix = sender.getPlatform().getLocaleManager().getTranslation(PREFIX); - if (prefix == null) { - prefix = PREFIX.getMessage(); - } - - String s = sender.getPlatform().getLocaleManager().getTranslation(this); - if (s == null) { - s = message; - } - - s = s.replace("{PREFIX}", prefix).replace("\\n", "\n"); - - if (showPrefix) { - sender.sendMessage(Util.color(prefix + format(s, objects))); - } else { - sender.sendMessage(Util.color(format(s, objects))); - } + sender.sendMessage(asString(sender.getPlatform().getLocaleManager(), objects)); } /** diff --git a/common/src/main/java/me/lucko/luckperms/common/contexts/ServerCalculator.java b/common/src/main/java/me/lucko/luckperms/common/contexts/ServerCalculator.java index b2cb96231..48d17161b 100644 --- a/common/src/main/java/me/lucko/luckperms/common/contexts/ServerCalculator.java +++ b/common/src/main/java/me/lucko/luckperms/common/contexts/ServerCalculator.java @@ -24,8 +24,6 @@ package me.lucko.luckperms.common.contexts; import lombok.AllArgsConstructor; -import com.google.common.collect.Maps; - import me.lucko.luckperms.api.context.ContextCalculator; import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.common.config.ConfigKeys; @@ -39,7 +37,10 @@ public class ServerCalculator implements ContextCalculator { @Override public MutableContextSet giveApplicableContext(T subject, MutableContextSet accumulator) { - accumulator.add(Maps.immutableEntry("server", config.get(ConfigKeys.SERVER))); + String server = config.get(ConfigKeys.SERVER); + if (!server.equals("global")) { + accumulator.add("server", server); + } return accumulator; } diff --git a/common/src/main/java/me/lucko/luckperms/common/core/DataMutateResult.java b/common/src/main/java/me/lucko/luckperms/common/core/DataMutateResult.java new file mode 100644 index 000000000..673b134ef --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/common/core/DataMutateResult.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.common.core; + +import lombok.AllArgsConstructor; + +import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; +import me.lucko.luckperms.exceptions.ObjectLacksException; + +import java.util.function.Supplier; + +@AllArgsConstructor +public enum DataMutateResult { + + SUCCESS(true, null), + ALREADY_HAS(false, ObjectAlreadyHasException::new), + LACKS(false, ObjectLacksException::new), + FAIL(false, RuntimeException::new); + + private boolean bool; + private final Supplier exceptionSupplier; + + public void throwException() { + if (exceptionSupplier != null) { + sneakyThrow(exceptionSupplier.get()); + } + } + + public boolean asBoolean() { + return bool; + } + + // allows us to throw checked exceptions without declaring it, as #throwException throws a number of + // exception types. + private static void sneakyThrow(Throwable t) { + sneakyThrow0(t); + } + + private static void sneakyThrow0(Throwable t) throws T { + throw (T) t; + } + +} diff --git a/common/src/main/java/me/lucko/luckperms/common/core/NodeBuilder.java b/common/src/main/java/me/lucko/luckperms/common/core/NodeBuilder.java index 2eb953c1c..813e6b673 100644 --- a/common/src/main/java/me/lucko/luckperms/common/core/NodeBuilder.java +++ b/common/src/main/java/me/lucko/luckperms/common/core/NodeBuilder.java @@ -22,6 +22,7 @@ package me.lucko.luckperms.common.core; +import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; @@ -40,8 +41,8 @@ import java.util.Set; /** * Builds Nodes */ -@RequiredArgsConstructor -public class NodeBuilder implements Node.Builder { +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +class NodeBuilder implements Node.Builder { private final String permission; private final MutableContextSet extraContexts = MutableContextSet.create(); private Boolean value = true; diff --git a/common/src/main/java/me/lucko/luckperms/common/core/NodeFactory.java b/common/src/main/java/me/lucko/luckperms/common/core/NodeFactory.java index 50930a471..2cf8045b7 100644 --- a/common/src/main/java/me/lucko/luckperms/common/core/NodeFactory.java +++ b/common/src/main/java/me/lucko/luckperms/common/core/NodeFactory.java @@ -32,9 +32,12 @@ import com.google.common.util.concurrent.UncheckedExecutionException; import me.lucko.luckperms.api.MetaUtils; import me.lucko.luckperms.api.Node; +import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.common.constants.Patterns; +import me.lucko.luckperms.common.core.model.Group; import java.util.List; +import java.util.Map; import java.util.concurrent.ExecutionException; /** @@ -118,7 +121,7 @@ public class NodeFactory { return new NodeBuilder(other); } - public static NodeBuilder makeMetaNode(String key, String value) { + public static Node.Builder makeMetaNode(String key, String value) { if (key.equalsIgnoreCase("prefix")) { return makePrefixNode(100, value); } @@ -129,15 +132,15 @@ public class NodeFactory { return new NodeBuilder("meta." + MetaUtils.escapeCharacters(key) + "." + MetaUtils.escapeCharacters(value)); } - public static NodeBuilder makeChatMetaNode(boolean prefix, int priority, String s) { + public static Node.Builder makeChatMetaNode(boolean prefix, int priority, String s) { return prefix ? makePrefixNode(priority, s) : makeSuffixNode(priority, s); } - public static NodeBuilder makePrefixNode(int priority, String prefix) { + public static Node.Builder makePrefixNode(int priority, String prefix) { return new NodeBuilder("prefix." + priority + "." + MetaUtils.escapeCharacters(prefix)); } - public static NodeBuilder makeSuffixNode(int priority, String suffix) { + public static Node.Builder makeSuffixNode(int priority, String suffix) { return new NodeBuilder("suffix." + priority + "." + MetaUtils.escapeCharacters(suffix)); } @@ -155,13 +158,7 @@ public class NodeFactory { sb.append(node.getGroupName()); } - if (node.isWorldSpecific()) { - sb.append(" ").append(node.getServer().get()).append(" ").append(node.getWorld().get()); - } else if (node.isServerSpecific()) { - sb.append(" ").append(node.getServer().get()); - } - - return sb.toString(); + return appendContextToCommand(sb, node).toString(); } sb.append(node.isTemporary() ? "permission settemp " : "permission set "); @@ -176,13 +173,28 @@ public class NodeFactory { sb.append(" ").append(node.getExpiryUnixTime()); } - if (node.isWorldSpecific()) { - sb.append(" ").append(node.getServer().get()).append(" ").append(node.getWorld().get()); - } else if (node.isServerSpecific()) { + return appendContextToCommand(sb, node).toString(); + } + + private static StringBuilder appendContextToCommand(StringBuilder sb, Node node) { + if (node.isServerSpecific()) { sb.append(" ").append(node.getServer().get()); + + if (node.isWorldSpecific()) { + sb.append(" ").append(node.getWorld().get()); + } + } else { + if (node.isWorldSpecific()) { + sb.append(" world=").append(node.getWorld().get()); + } } - return sb.toString(); + ContextSet contexts = node.getContexts(); + for (Map.Entry context : contexts.toSet()) { + sb.append(" ").append(context.getKey()).append("=").append(context.getValue()); + } + + return sb; } public static String escapeDelimiters(String s, String... delims) { @@ -298,4 +310,41 @@ public class NodeFactory { public static Node make(String node, boolean value, String server, String world, long expireAt) { return newBuilder(node).setValue(value).setServer(server).setWorld(world).setExpiry(expireAt).build(); } + + public static Node make(Group group, long expireAt) { + return NodeFactory.make("group." + group.getName(), true, expireAt); + } + + public static Node make(Group group, String server, long expireAt) { + return NodeFactory.make("group." + group.getName(), true, server, expireAt); + } + + public static Node make(Group group, String server, String world, long expireAt) { + return NodeFactory.make("group." + group.getName(), true, server, world, expireAt); + } + + public static Node make(Group group) { + return make("group." + group.getName()); + } + + public static Node make(Group group, boolean temporary) { + return make("group." + group.getName(), temporary); + } + + public static Node make(Group group, String server) { + return make("group." + group.getName(), server); + } + + public static Node make(Group group, String server, String world) { + return make("group." + group.getName(), server, world); + } + + public static Node make(Group group, String server, boolean temporary) { + return make("group." + group.getName(), server, temporary); + } + + public static Node make(Group group, String server, String world, boolean temporary) { + return make("group." + group.getName(), server, world, temporary); + } + } diff --git a/common/src/main/java/me/lucko/luckperms/common/core/model/ImmutableNode.java b/common/src/main/java/me/lucko/luckperms/common/core/model/ImmutableNode.java index fc2710365..832258a08 100644 --- a/common/src/main/java/me/lucko/luckperms/common/core/model/ImmutableNode.java +++ b/common/src/main/java/me/lucko/luckperms/common/core/model/ImmutableNode.java @@ -195,25 +195,20 @@ public class ImmutableNode implements Node { throw new IllegalArgumentException("Empty permission"); } + // standardize server/world values. if (server != null) { server = server.toLowerCase(); } if (world != null) { world = world.toLowerCase(); } - if (server != null && (server.equals("global") || server.equals(""))) { server = null; } - if (world != null && (world.equals("global") || world.equals(""))) { world = null; } - if (world != null && server == null) { - server = "global"; - } - this.permission = NodeFactory.unescapeDelimiters(permission, "/", "-", "$", "(", ")", "=", ","); this.value = value; this.override = override; @@ -289,7 +284,7 @@ public class ImmutableNode implements Node { @Override public boolean isServerSpecific() { - return server != null && !server.equalsIgnoreCase("global"); + return server != null; } @Override @@ -297,6 +292,16 @@ public class ImmutableNode implements Node { return world != null; } + @Override + public boolean appliesGlobally() { + return server == null && world == null && contexts.isEmpty(); + } + + @Override + public boolean hasSpecificContext() { + return server != null && world != null && !contexts.isEmpty(); + } + @Override public boolean isTemporary() { return expireAt != 0L; diff --git a/common/src/main/java/me/lucko/luckperms/common/core/model/PermissionHolder.java b/common/src/main/java/me/lucko/luckperms/common/core/model/PermissionHolder.java index d71599818..f0ce26ed2 100644 --- a/common/src/main/java/me/lucko/luckperms/common/core/model/PermissionHolder.java +++ b/common/src/main/java/me/lucko/luckperms/common/core/model/PermissionHolder.java @@ -29,6 +29,7 @@ import lombok.RequiredArgsConstructor; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; +import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.SortedSetMultimap; @@ -45,6 +46,7 @@ import me.lucko.luckperms.common.caching.handlers.GroupReference; import me.lucko.luckperms.common.caching.handlers.HolderReference; import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.core.ContextSetComparator; +import me.lucko.luckperms.common.core.DataMutateResult; import me.lucko.luckperms.common.core.InheritanceInfo; import me.lucko.luckperms.common.core.NodeComparator; import me.lucko.luckperms.common.core.NodeFactory; @@ -54,8 +56,6 @@ import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.utils.ExtractedContexts; import me.lucko.luckperms.common.utils.ImmutableLocalizedNode; import me.lucko.luckperms.common.utils.NodeTools; -import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; -import me.lucko.luckperms.exceptions.ObjectLacksException; import java.util.ArrayList; import java.util.Collection; @@ -704,7 +704,7 @@ public abstract class PermissionHolder { * @return a tristate */ public Tristate hasPermission(Node node, boolean checkTransient) { - if (node.isGroupNode() && node.getGroupName().equalsIgnoreCase(getObjectName())) { + if (this instanceof Group && node.isGroupNode() && node.getGroupName().equalsIgnoreCase(getObjectName())) { return Tristate.TRUE; } @@ -793,11 +793,10 @@ public abstract class PermissionHolder { * Sets a permission node * * @param node the node to set - * @throws ObjectAlreadyHasException if the holder has this permission already */ - public void setPermission(Node node) throws ObjectAlreadyHasException { + public DataMutateResult setPermission(Node node) { if (hasPermission(node, false) != Tristate.UNDEFINED) { - throw new ObjectAlreadyHasException(); + return DataMutateResult.ALREADY_HAS; } ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); @@ -810,12 +809,7 @@ public abstract class PermissionHolder { ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); - } - - public void setPermissionUnchecked(Node node) { - try { - setPermission(node); - } catch (ObjectAlreadyHasException ignored) {} + return DataMutateResult.SUCCESS; } /** @@ -823,9 +817,8 @@ public abstract class PermissionHolder { * @param node the node to set * @param modifier the modifier to use for the operation * @return the node that was actually set, respective of the modifier - * @throws ObjectAlreadyHasException if the holder has this permission set already, respective of the modifier */ - public Node setPermission(Node node, TemporaryModifier modifier) throws ObjectAlreadyHasException { + public Map.Entry setPermission(Node node, TemporaryModifier modifier) { // If the node is temporary, we should take note of the modifier if (node.isTemporary()) { if (modifier == TemporaryModifier.ACCUMULATE) { @@ -850,7 +843,7 @@ public abstract class PermissionHolder { invalidateCache(); ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeAdd(newNode, this, before, after); - return newNode; + return Maps.immutableEntry(DataMutateResult.SUCCESS, newNode); } } else if (modifier == TemporaryModifier.REPLACE) { @@ -874,7 +867,7 @@ public abstract class PermissionHolder { invalidateCache(); ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); - return node; + return Maps.immutableEntry(DataMutateResult.SUCCESS, node); } } } @@ -883,25 +876,17 @@ public abstract class PermissionHolder { } // Fallback to the normal handling. - setPermission(node); - return node; - } - - public void setPermissionUnchecked(Node node, TemporaryModifier modifier) { - try { - setPermission(node, modifier); - } catch (ObjectAlreadyHasException ignored) {} + return Maps.immutableEntry(setPermission(node), node); } /** * Sets a transient permission node * * @param node the node to set - * @throws ObjectAlreadyHasException if the holder has this permission already */ - public void setTransientPermission(Node node) throws ObjectAlreadyHasException { + public DataMutateResult setTransientPermission(Node node) { if (hasPermission(node, true) != Tristate.UNDEFINED) { - throw new ObjectAlreadyHasException(); + return DataMutateResult.ALREADY_HAS; } ImmutableSet before = ImmutableSet.copyOf(getTransientNodes().values()); @@ -914,23 +899,17 @@ public abstract class PermissionHolder { ImmutableSet after = ImmutableSet.copyOf(getTransientNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); - } - - public void setTransientPermissionUnchecked(Node node) { - try { - setTransientPermission(node); - } catch (ObjectAlreadyHasException ignored) {} + return DataMutateResult.SUCCESS; } /** * Unsets a permission node * * @param node the node to unset - * @throws ObjectLacksException if the holder doesn't have this node already */ - public void unsetPermission(Node node) throws ObjectLacksException { + public DataMutateResult unsetPermission(Node node) { if (hasPermission(node, false) == Tristate.UNDEFINED) { - throw new ObjectLacksException(); + return DataMutateResult.LACKS; } ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); @@ -942,21 +921,15 @@ public abstract class PermissionHolder { ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); - } - - public void unsetPermissionUnchecked(Node node) { - try { - unsetPermission(node); - } catch (ObjectLacksException ignored) {} + return DataMutateResult.SUCCESS; } /** * Unsets a permission node * * @param node the node to unset - * @throws ObjectLacksException if the holder doesn't have this node already */ - public void unsetPermissionExact(Node node) throws ObjectLacksException { + public DataMutateResult unsetPermissionExact(Node node) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { @@ -967,21 +940,21 @@ public abstract class PermissionHolder { ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); if (before.size() == after.size()) { - throw new ObjectLacksException(); + return DataMutateResult.LACKS; } plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); + return DataMutateResult.SUCCESS; } /** * Unsets a transient permission node * * @param node the node to unset - * @throws ObjectLacksException if the holder doesn't have this node already */ - public void unsetTransientPermission(Node node) throws ObjectLacksException { + public DataMutateResult unsetTransientPermission(Node node) { if (hasPermission(node, true) == Tristate.UNDEFINED) { - throw new ObjectLacksException(); + return DataMutateResult.LACKS; } ImmutableSet before = ImmutableSet.copyOf(getTransientNodes().values()); @@ -993,12 +966,7 @@ public abstract class PermissionHolder { ImmutableSet after = ImmutableSet.copyOf(getTransientNodes().values()); plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); - } - - public void unsetTransientPermissionUnchecked(Node node) { - try { - unsetTransientPermission(node); - } catch (ObjectLacksException ignored) {} + return DataMutateResult.SUCCESS; } public boolean inheritsGroup(Group group) { @@ -1013,76 +981,12 @@ public abstract class PermissionHolder { return group.getName().equalsIgnoreCase(this.getObjectName()) || hasPermission("group." + group.getName(), true, server, world); } - public void setInheritGroup(Group group) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true)); + public DataMutateResult setInheritGroup(Group group, ContextSet contexts) { + return setPermission(NodeFactory.newBuilder("group." + group.getName()).withExtraContext(contexts).build()); } - public void setInheritGroup(Group group, String server) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true, server)); - } - - public void setInheritGroup(Group group, String server, String world) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true, server, world)); - } - - public void setInheritGroup(Group group, long expireAt) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true, expireAt)); - } - - public void setInheritGroup(Group group, String server, long expireAt) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true, server, expireAt)); - } - - public void setInheritGroup(Group group, String server, String world, long expireAt) throws ObjectAlreadyHasException { - if (group.getName().equalsIgnoreCase(this.getObjectName())) { - throw new ObjectAlreadyHasException(); - } - - setPermission(NodeFactory.make("group." + group.getName(), true, server, world, expireAt)); - } - - public void unsetInheritGroup(Group group) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName())); - } - - public void unsetInheritGroup(Group group, boolean temporary) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName(), temporary)); - } - - public void unsetInheritGroup(Group group, String server) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName(), server)); - } - - public void unsetInheritGroup(Group group, String server, String world) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName(), server, world)); - } - - public void unsetInheritGroup(Group group, String server, boolean temporary) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName(), server, temporary)); - } - - public void unsetInheritGroup(Group group, String server, String world, boolean temporary) throws ObjectLacksException { - unsetPermission(NodeFactory.make("group." + group.getName(), server, world, temporary)); + public DataMutateResult unsetInheritGroup(Group group, ContextSet contexts) { + return unsetPermission(NodeFactory.newBuilder("group." + group.getName()).withExtraContext(contexts).build()); } /** @@ -1098,32 +1002,10 @@ public abstract class PermissionHolder { plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); } - public void clearNodes(String server) { - String finalServer = Optional.ofNullable(server).orElse("global"); - + public void clearNodes(ContextSet contextSet) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { - if (!nodes.values().removeIf(n -> n.getServer().orElse("global").equalsIgnoreCase(finalServer))) { - return; - } - } - invalidateCache(); - ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); - plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); - } - - public void clearNodes(String server, String world) { - String finalServer = Optional.ofNullable(server).orElse("global"); - String finalWorld = Optional.ofNullable(world).orElse("null"); - - ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); - synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - n.getServer().orElse("global").equalsIgnoreCase(finalServer) && - n.getWorld().orElse("null").equalsIgnoreCase(finalWorld)); - if (!b) { - return; - } + nodes.removeAll(contextSet.makeImmutable()); } invalidateCache(); ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); @@ -1147,37 +1029,15 @@ public abstract class PermissionHolder { plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); } - public void clearParents(String server, boolean giveDefault) { - String finalServer = Optional.ofNullable(server).orElse("global"); - + public void clearParents(ContextSet contextSet, boolean giveDefault) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - n.isGroupNode() && n.getServer().orElse("global").equalsIgnoreCase(finalServer) - ); - if (!b) { + SortedSet nodes = this.nodes.get(contextSet.makeImmutable()); + if (nodes == null) { return; } - } - if (this instanceof User && giveDefault) { - plugin.getUserManager().giveDefaultIfNeeded((User) this, false); - } - invalidateCache(); - ImmutableSet after = ImmutableSet.copyOf(getNodes().values()); - plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); - } - public void clearParents(String server, String world, boolean giveDefault) { - String finalServer = Optional.ofNullable(server).orElse("global"); - String finalWorld = Optional.ofNullable(world).orElse("null"); - - ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); - synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - n.isGroupNode() && - n.getServer().orElse("global").equalsIgnoreCase(finalServer) && - n.getWorld().orElse("null").equalsIgnoreCase(finalWorld) - ); + boolean b = nodes.removeIf(Node::isGroupNode); if (!b) { return; } @@ -1203,15 +1063,15 @@ public abstract class PermissionHolder { plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); } - public void clearMeta(String server) { - String finalServer = Optional.ofNullable(server).orElse("global"); - + public void clearMeta(ContextSet contextSet) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - (n.isMeta() || n.isPrefix() || n.isSuffix()) && - n.getServer().orElse("global").equalsIgnoreCase(finalServer) - ); + SortedSet nodes = this.nodes.get(contextSet.makeImmutable()); + if (nodes == null) { + return; + } + + boolean b = nodes.removeIf(n -> n.isMeta() || n.isPrefix() || n.isSuffix()); if (!b) { return; } @@ -1221,18 +1081,10 @@ public abstract class PermissionHolder { plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); } - public void clearMeta(String server, String world) { - String finalServer = Optional.ofNullable(server).orElse("global"); - String finalWorld = Optional.ofNullable(world).orElse("null"); - + public void clearMetaKeys(String key, boolean temp) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - (n.isMeta() || n.isPrefix() || n.isSuffix()) && ( - n.getServer().orElse("global").equalsIgnoreCase(finalServer) && - n.getWorld().orElse("null").equalsIgnoreCase(finalWorld) - ) - ); + boolean b = this.nodes.values().removeIf(n -> n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key)); if (!b) { return; } @@ -1242,17 +1094,16 @@ public abstract class PermissionHolder { plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); } - public void clearMetaKeys(String key, String server, String world, boolean temp) { - String finalServer = Optional.ofNullable(server).orElse("global"); - String finalWorld = Optional.ofNullable(world).orElse("null"); - + public void clearMetaKeys(String key, ContextSet contextSet, boolean temp) { ImmutableSet before = ImmutableSet.copyOf(getNodes().values()); synchronized (nodes) { - boolean b = nodes.values().removeIf(n -> - n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key) && - n.getServer().orElse("global").equalsIgnoreCase(finalServer) && - n.getWorld().orElse("null").equalsIgnoreCase(finalWorld) - ); + + SortedSet nodes = this.nodes.get(contextSet.makeImmutable()); + if (nodes == null) { + return; + } + + boolean b = nodes.removeIf(n -> n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key)); if (!b) { return; } @@ -1321,18 +1172,6 @@ public abstract class PermissionHolder { return weight; } - /** - * Get a {@link List} of all of the groups the holder inherits, on all servers - * - * @return a {@link List} of group names - */ - public List getGroupNames() { - return mergePermissionsToList().stream() - .filter(Node::isGroupNode) - .map(Node::getGroupName) - .collect(Collectors.toList()); - } - public Set getGroupReferences() { return mergePermissionsToList().stream() .filter(Node::isGroupNode) @@ -1341,43 +1180,4 @@ public abstract class PermissionHolder { .map(GroupReference::of) .collect(Collectors.toSet()); } - - /** - * Get a {@link List} of the groups the holder inherits on a specific server and world - * - * @param server the server to check - * @param world the world to check - * @return a {@link List} of group names - */ - public List getLocalGroups(String server, String world) { - return mergePermissionsToList().stream() - .filter(Node::isGroupNode) - .filter(n -> n.shouldApplyOnWorld(world, false, true)) - .filter(n -> n.shouldApplyOnServer(server, false, true)) - .map(Node::getGroupName) - .collect(Collectors.toList()); - } - - public List getLocalGroups(String server, String world, boolean includeGlobal) { - return mergePermissionsToList().stream() - .filter(Node::isGroupNode) - .filter(n -> n.shouldApplyOnWorld(world, includeGlobal, true)) - .filter(n -> n.shouldApplyOnServer(server, includeGlobal, true)) - .map(Node::getGroupName) - .collect(Collectors.toList()); - } - - /** - * Get a {@link List} of the groups the holder inherits on a specific server - * - * @param server the server to check - * @return a {@link List} of group names - */ - public List getLocalGroups(String server) { - return mergePermissionsToList().stream() - .filter(Node::isGroupNode) - .filter(n -> n.shouldApplyOnServer(server, false, true)) - .map(Node::getGroupName) - .collect(Collectors.toList()); - } } diff --git a/common/src/main/java/me/lucko/luckperms/common/defaults/Rule.java b/common/src/main/java/me/lucko/luckperms/common/defaults/Rule.java index f346d0b29..9dd04b566 100644 --- a/common/src/main/java/me/lucko/luckperms/common/defaults/Rule.java +++ b/common/src/main/java/me/lucko/luckperms/common/defaults/Rule.java @@ -89,11 +89,11 @@ public class Rule { // The holder meets all of the requirements of this rule. for (String s : toTake) { - user.unsetPermissionUnchecked(NodeFactory.fromSerialisedNode(s, true)); + user.unsetPermission(NodeFactory.fromSerialisedNode(s, true)); } for (String s : toGive) { - user.setPermissionUnchecked(NodeFactory.fromSerialisedNode(s, true)); + user.setPermission(NodeFactory.fromSerialisedNode(s, true)); } if (setPrimaryGroup != null) { diff --git a/common/src/main/java/me/lucko/luckperms/common/managers/impl/GenericUserManager.java b/common/src/main/java/me/lucko/luckperms/common/managers/impl/GenericUserManager.java index 01a937708..6916de2e4 100644 --- a/common/src/main/java/me/lucko/luckperms/common/managers/impl/GenericUserManager.java +++ b/common/src/main/java/me/lucko/luckperms/common/managers/impl/GenericUserManager.java @@ -42,7 +42,7 @@ public class GenericUserManager extends AbstractManager im if (user.getPrimaryGroup().getStoredValue() != null && !user.getPrimaryGroup().getStoredValue().isEmpty()) { for (Node node : user.getNodes().values()) { - if (node.isServerSpecific() || node.isWorldSpecific()) { + if (node.hasSpecificContext()) { continue; } @@ -58,7 +58,7 @@ public class GenericUserManager extends AbstractManager im } user.getPrimaryGroup().setStoredValue("default"); - user.setPermissionUnchecked(NodeFactory.make("group.default")); + user.setPermission(NodeFactory.make("group.default")); if (save) { plugin.getStorage().saveUser(user); diff --git a/common/src/main/java/me/lucko/luckperms/common/storage/backing/utils/NodeDataHolder.java b/common/src/main/java/me/lucko/luckperms/common/storage/backing/utils/NodeDataHolder.java index fd041c61b..7fcecef53 100644 --- a/common/src/main/java/me/lucko/luckperms/common/storage/backing/utils/NodeDataHolder.java +++ b/common/src/main/java/me/lucko/luckperms/common/storage/backing/utils/NodeDataHolder.java @@ -27,15 +27,20 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSetMultimap; import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import me.lucko.luckperms.api.Node; -import me.lucko.luckperms.common.core.NodeBuilder; +import me.lucko.luckperms.common.core.NodeFactory; -import java.lang.reflect.Type; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.Map; @Getter @@ -44,7 +49,6 @@ import java.util.Map; @AllArgsConstructor(staticName = "of") public class NodeDataHolder { private static final Gson GSON = new Gson(); - private static final Type CONTEXT_TYPE = new TypeToken>>(){}.getType(); public static NodeDataHolder fromNode(Node node) { return NodeDataHolder.of( @@ -58,12 +62,19 @@ public class NodeDataHolder { } public static NodeDataHolder of(String permission, boolean value, String server, String world, long expiry, String contexts) { - Map> deserializedContexts = GSON.fromJson(contexts, CONTEXT_TYPE); + JsonObject context = GSON.fromJson(contexts, JsonObject.class); ImmutableSetMultimap.Builder map = ImmutableSetMultimap.builder(); - for (Map.Entry> e : deserializedContexts.entrySet()) { - map.putAll(e.getKey(), e.getValue()); + for (Map.Entry e : context.entrySet()) { + JsonElement val = e.getValue(); + if (val.isJsonArray()) { + JsonArray vals = val.getAsJsonArray(); + for (JsonElement element : vals) { + map.put(e.getKey(), element.getAsString()); + } + } else { + map.put(e.getKey(), val.getAsString()); + } } - return new NodeDataHolder(permission, value, server, world, expiry, map.build()); } @@ -75,11 +86,29 @@ public class NodeDataHolder { private final ImmutableSetMultimap contexts; public String serialiseContext() { - return GSON.toJson(getContexts().asMap()); + JsonObject context = new JsonObject(); + ImmutableMap> map = getContexts().asMap(); + + map.forEach((key, value) -> { + List vals = new ArrayList<>(value); + int size = vals.size(); + + if (size == 1) { + context.addProperty(key, vals.get(0)); + } else if (size > 1) { + JsonArray arr = new JsonArray(); + for (String s : vals) { + arr.add(new JsonPrimitive(s)); + } + context.add(key, arr); + } + }); + + return GSON.toJson(context); } public Node toNode() { - NodeBuilder builder = new NodeBuilder(permission); + Node.Builder builder = NodeFactory.newBuilder(permission); builder.setValue(value); builder.setServer(server); builder.setWorld(world); diff --git a/sponge/src/main/java/me/lucko/luckperms/sponge/SpongeSenderFactory.java b/sponge/src/main/java/me/lucko/luckperms/sponge/SpongeSenderFactory.java index 58fb3574e..f8812683b 100644 --- a/sponge/src/main/java/me/lucko/luckperms/sponge/SpongeSenderFactory.java +++ b/sponge/src/main/java/me/lucko/luckperms/sponge/SpongeSenderFactory.java @@ -64,7 +64,7 @@ public class SpongeSenderFactory extends SenderFactory { @Override protected void sendMessage(CommandSource source, FancyMessage message) { try { - source.sendMessage(TextSerializers.JSON.deserialize(message.toJSONString())); + source.sendMessage(TextSerializers.JSON.deserialize(message.exportToJson())); } catch (Exception e) { sendMessage(source, message.toOldMessageFormat()); } diff --git a/sponge/src/main/java/me/lucko/luckperms/sponge/migration/SpongeMigrationUtils.java b/sponge/src/main/java/me/lucko/luckperms/sponge/migration/SpongeMigrationUtils.java index 2f3e428b4..e808bbaba 100644 --- a/sponge/src/main/java/me/lucko/luckperms/sponge/migration/SpongeMigrationUtils.java +++ b/sponge/src/main/java/me/lucko/luckperms/sponge/migration/SpongeMigrationUtils.java @@ -26,7 +26,6 @@ import lombok.experimental.UtilityClass; import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.common.commands.impl.migration.MigrationUtils; -import me.lucko.luckperms.common.core.NodeBuilder; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -63,7 +62,7 @@ public class SpongeMigrationUtils { String world = extractedContexts.getWorld(); for (Map.Entry perm : e.getValue().entrySet()) { - holder.setPermissionUnchecked(new NodeBuilder(perm.getKey()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(perm.getValue()).build()); + holder.setPermission(NodeFactory.newBuilder(perm.getKey()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(perm.getValue()).build()); } } @@ -79,11 +78,11 @@ public class SpongeMigrationUtils { for (Map.Entry opt : e.getValue().entrySet()) { if (opt.getKey().equalsIgnoreCase("prefix")) { - holder.setPermissionUnchecked(NodeFactory.makePrefixNode(priority, opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); + holder.setPermission(NodeFactory.makePrefixNode(priority, opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); } else if (opt.getKey().equalsIgnoreCase("suffix")) { - holder.setPermissionUnchecked(NodeFactory.makeSuffixNode(priority, opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); + holder.setPermission(NodeFactory.makeSuffixNode(priority, opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); } else { - holder.setPermissionUnchecked(NodeFactory.makeMetaNode(opt.getKey(), opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); + holder.setPermission(NodeFactory.makeMetaNode(opt.getKey(), opt.getValue()).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); } } } @@ -103,7 +102,7 @@ public class SpongeMigrationUtils { continue; // LuckPerms does not support persisting other subject types. } - holder.setPermissionUnchecked(new NodeBuilder("group." + MigrationUtils.standardizeName(s.getIdentifier())).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); + holder.setPermission(NodeFactory.newBuilder("group." + MigrationUtils.standardizeName(s.getIdentifier())).setServer(server).setWorld(world).withExtraContext(contexts).setValue(true).build()); } } } diff --git a/sponge/src/main/java/me/lucko/luckperms/sponge/service/LuckPermsSubjectData.java b/sponge/src/main/java/me/lucko/luckperms/sponge/service/LuckPermsSubjectData.java index 3728c97a8..2962884bf 100644 --- a/sponge/src/main/java/me/lucko/luckperms/sponge/service/LuckPermsSubjectData.java +++ b/sponge/src/main/java/me/lucko/luckperms/sponge/service/LuckPermsSubjectData.java @@ -34,7 +34,6 @@ import me.lucko.luckperms.api.Tristate; import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ImmutableContextSet; import me.lucko.luckperms.common.caching.MetaAccumulator; -import me.lucko.luckperms.common.core.NodeBuilder; import me.lucko.luckperms.common.core.NodeFactory; import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.PermissionHolder; @@ -93,31 +92,31 @@ public class LuckPermsSubjectData implements LPSubjectData { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_PERMISSION)) { if (tristate == Tristate.UNDEFINED) { // Unset - Node node = new NodeBuilder(permission).withExtraContext(contexts).build(); + Node node = NodeFactory.newBuilder(permission).withExtraContext(contexts).build(); if (enduring) { - holder.unsetPermissionUnchecked(node); + holder.unsetPermission(node); } else { - holder.unsetTransientPermissionUnchecked(node); + holder.unsetTransientPermission(node); } objectSave(holder); return true; } - Node node = new NodeBuilder(permission).setValue(tristate.asBoolean()).withExtraContext(contexts).build(); + Node node = NodeFactory.newBuilder(permission).setValue(tristate.asBoolean()).withExtraContext(contexts).build(); // Workaround: unset the inverse, to allow false -> true, true -> false overrides. if (enduring) { - holder.unsetPermissionUnchecked(node); + holder.unsetPermission(node); } else { - holder.unsetTransientPermissionUnchecked(node); + holder.unsetTransientPermission(node); } if (enduring) { - holder.setPermissionUnchecked(node); + holder.setPermission(node); } else { - holder.setTransientPermissionUnchecked(node); + holder.setTransientPermission(node); } objectSave(holder); @@ -188,11 +187,11 @@ public class LuckPermsSubjectData implements LPSubjectData { LPSubject permsSubject = subject.resolve(service); if (enduring) { - holder.setPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) + holder.setPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier()) .withExtraContext(contexts) .build()); } else { - holder.setTransientPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) + holder.setTransientPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier()) .withExtraContext(contexts) .build()); } @@ -211,11 +210,11 @@ public class LuckPermsSubjectData implements LPSubjectData { LPSubject permsSubject = subject.resolve(service); if (enduring) { - holder.unsetPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) + holder.unsetPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier()) .withExtraContext(contexts) .build()); } else { - holder.unsetTransientPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) + holder.unsetTransientPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier()) .withExtraContext(contexts) .build()); } @@ -337,9 +336,9 @@ public class LuckPermsSubjectData implements LPSubjectData { priority += 10; if (enduring) { - holder.setPermissionUnchecked(NodeFactory.makeChatMetaNode(type.equals("prefix"), priority, value).withExtraContext(context).build()); + holder.setPermission(NodeFactory.makeChatMetaNode(type.equals("prefix"), priority, value).withExtraContext(context).build()); } else { - holder.setTransientPermissionUnchecked(NodeFactory.makeChatMetaNode(type.equals("prefix"), priority, value).withExtraContext(context).build()); + holder.setTransientPermission(NodeFactory.makeChatMetaNode(type.equals("prefix"), priority, value).withExtraContext(context).build()); } } else { @@ -352,9 +351,9 @@ public class LuckPermsSubjectData implements LPSubjectData { toRemove.forEach(makeUnsetConsumer(enduring)); if (enduring) { - holder.setPermissionUnchecked(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build()); + holder.setPermission(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build()); } else { - holder.setTransientPermissionUnchecked(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build()); + holder.setTransientPermission(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build()); } } @@ -422,9 +421,9 @@ public class LuckPermsSubjectData implements LPSubjectData { private Consumer makeUnsetConsumer(boolean enduring) { return n -> { if (enduring) { - holder.unsetPermissionUnchecked(n); + holder.unsetPermission(n); } else { - holder.unsetTransientPermissionUnchecked(n); + holder.unsetTransientPermission(n); } }; }