Allow context pairs to be specified in commands, fix misuse of exceptions in the permission holder class

This commit is contained in:
Luck 2017-04-02 18:44:05 +01:00
parent 0a33c0aac5
commit e7e2e3f7e0
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
85 changed files with 1572 additions and 2359 deletions

View File

@ -85,15 +85,35 @@ public interface Node extends Map.Entry<String, Boolean> {
Optional<String> getWorld(); Optional<String> getWorld();
/** /**
* Returns if this node is server specific
*
* @return true if this node is server specific * @return true if this node is server specific
*/ */
boolean isServerSpecific(); boolean isServerSpecific();
/** /**
* Returns if this node is server specific
*
* @return true if this node is server specific * @return true if this node is server specific
*/ */
boolean isWorldSpecific(); 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 * If this node should apply on a specific server
* *
@ -222,22 +242,30 @@ public interface Node extends Map.Entry<String, Boolean> {
* Converts this node into a serialized form * Converts this node into a serialized form
* *
* @return a serialized node string * @return a serialized node string
* @deprecated because this serialized form is no longer used by the implementation.
*/ */
@Deprecated
String toSerializedNode(); String toSerializedNode();
/** /**
* Returns if this is a group node
*
* @return true if this is a group node * @return true if this is a group node
*/ */
boolean isGroupNode(); boolean isGroupNode();
/** /**
* Returns the name of the group
*
* @return the name of the group * @return the name of the group
* @throws IllegalStateException if this is not a group node. See {@link #isGroupNode()} * @throws IllegalStateException if this is not a group node. See {@link #isGroupNode()}
*/ */
String getGroupName(); 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(); boolean isWildcard();
@ -250,6 +278,8 @@ public interface Node extends Map.Entry<String, Boolean> {
int getWildcardLevel(); int getWildcardLevel();
/** /**
* Returns if this node is a meta node
*
* @return true if this node is a meta node * @return true if this node is a meta node
*/ */
boolean isMeta(); boolean isMeta();

View File

@ -37,7 +37,7 @@ import java.util.Set;
public interface ContextSet { public interface ContextSet {
/** /**
* Make a singleton ImmutableContextSet from a context pair * Creates an ImmutableContextSet from a context pair
* *
* @param key the key * @param key the key
* @param value the value * @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 * @param map the map to copy from
* @return a new ImmutableContextSet representing the pairs from the map * @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 * @param iterable the iterable to copy from
* @return a new ImmutableContextSet representing the pairs in the iterable * @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 * @param multimap the multimap to copy from
* @return a new ImmutableContextSet representing the pairs in the multimap * @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. * Only really useful for converting between mutable and immutable types.
* *
* @param contextSet the context set to copy from * @param contextSet the context set to copy from
@ -173,6 +188,7 @@ public interface ContextSet {
* *
* @param key the key to find values for * @param key the key to find values for
* @return an optional containing any match * @return an optional containing any match
* @since 3.1
*/ */
default Optional<String> getAnyValue(String key) { default Optional<String> getAnyValue(String key) {
return getValues(key).stream().findAny(); return getValues(key).stream().findAny();
@ -203,6 +219,7 @@ public interface ContextSet {
* *
* @param other the other set to check * @param other the other set to check
* @return true if all entries in this set are also in the other set * @return true if all entries in this set are also in the other set
* @since 3.1
*/ */
default boolean isSatisfiedBy(ContextSet other) { default boolean isSatisfiedBy(ContextSet other) {
if (this.isEmpty()) { if (this.isEmpty()) {

View File

@ -41,7 +41,7 @@ public final class ImmutableContextSet implements ContextSet {
private static final ImmutableContextSet EMPTY = new ImmutableContextSet(ImmutableSetMultimap.of()); 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 key the key
* @param value the value * @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 * @param map the map to copy from
* @return a new ImmutableContextSet representing the pairs from the map * @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 * @param iterable the iterable to copy from
* @return a new ImmutableContextSet representing the pairs in the iterable * @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 * @param multimap the multimap to copy from
* @return a new ImmutableContextSet representing the pairs in the multimap * @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 * @return a new ContextSet
*/ */

View File

@ -62,6 +62,36 @@ public final class MutableContextSet implements ContextSet {
return set; 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 * Creates a MutableContextSet from an existing map
* *

View File

@ -39,7 +39,7 @@ public class MessageHandler {
public void sendJsonMessage(CommandSender sender, FancyMessage message) { public void sendJsonMessage(CommandSender sender, FancyMessage message) {
if (ReflectionUtil.isChatCompatible() && sender instanceof Player) { if (ReflectionUtil.isChatCompatible() && sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
String json = message.toJSONString(); String json = message.exportToJson();
// Try Bukkit. // Try Bukkit.
if (bukkitHandler.sendJsonMessage(player, json)) { if (bukkitHandler.sendJsonMessage(player, json)) {

View File

@ -189,11 +189,11 @@ public class MigrationBPermissions extends SubCommand<Object> {
private static void migrateHolder(World world, Calculable c, PermissionHolder holder) { private static void migrateHolder(World world, Calculable c, PermissionHolder holder) {
// Migrate the groups permissions in this world // Migrate the groups permissions in this world
for (Permission p : c.getPermissions()) { 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 // Include any child permissions
for (Map.Entry<String, Boolean> child : p.getChildren().entrySet()) { for (Map.Entry<String, Boolean> 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<Object> {
parentName = "default"; 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 // Migrate existing meta
for (Map.Entry<String, String> meta : c.getMeta().entrySet()) { for (Map.Entry<String, String> meta : c.getMeta().entrySet()) {
if (meta.getKey().equalsIgnoreCase("prefix") || meta.getKey().equalsIgnoreCase("suffix")) { 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; 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());
} }
} }
} }

View File

@ -97,11 +97,11 @@ public class MigrationGroupManager extends SubCommand<Object> {
me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(groupName); me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(groupName);
for (String node : g.getPermissionList()) { for (String node : g.getPermissionList()) {
group.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); group.setPermission(MigrationUtils.parseNode(node, true).build());
} }
for (String s : g.getInherits()) { 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); plugin.getStorage().saveGroup(group);
@ -217,7 +217,7 @@ public class MigrationGroupManager extends SubCommand<Object> {
me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(e.getKey()); me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(e.getKey());
for (Node node : e.getValue()) { for (Node node : e.getValue()) {
group.setPermissionUnchecked(node); group.setPermission(node);
} }
plugin.getStorage().saveGroup(group); plugin.getStorage().saveGroup(group);
@ -232,14 +232,14 @@ public class MigrationGroupManager extends SubCommand<Object> {
me.lucko.luckperms.common.core.model.User user = plugin.getUserManager().get(e.getKey()); me.lucko.luckperms.common.core.model.User user = plugin.getUserManager().get(e.getKey());
for (Node node : e.getValue()) { for (Node node : e.getValue()) {
user.setPermissionUnchecked(node); user.setPermission(node);
} }
String primaryGroup = primaryGroups.get(e.getKey()); String primaryGroup = primaryGroups.get(e.getKey());
if (primaryGroup != null) { if (primaryGroup != null) {
user.setPermissionUnchecked(NodeFactory.make("group." + primaryGroup)); user.setPermission(NodeFactory.make("group." + primaryGroup));
user.getPrimaryGroup().setStoredValue(primaryGroup); user.getPrimaryGroup().setStoredValue(primaryGroup);
user.unsetPermissionUnchecked(NodeFactory.make("group.default")); user.unsetPermission(NodeFactory.make("group.default"));
} }
plugin.getStorage().saveUser(user); plugin.getStorage().saveUser(user);

View File

@ -106,7 +106,7 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
try { try {
for (String node : group.getOwnPermissions(null)) { for (String node : group.getOwnPermissions(null)) {
lpGroup.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); lpGroup.setPermission(MigrationUtils.parseNode(node, true).build());
} }
} catch (NullPointerException ignored) { } catch (NullPointerException ignored) {
// No docs on if #getOwnPermissions(null) is ok. Should be fine though. // No docs on if #getOwnPermissions(null) is ok. Should be fine though.
@ -114,17 +114,17 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
for (String world : worlds) { for (String world : worlds) {
for (String node : group.getOwnPermissions(world)) { 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()) { 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 (String world : worlds) {
for (PermissionGroup g : group.getParents(world)) { 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<Object> {
String suffix = group.getOwnSuffix(); String suffix = group.getOwnSuffix();
if (prefix != null && !prefix.equals("")) { if (prefix != null && !prefix.equals("")) {
lpGroup.setPermissionUnchecked(NodeFactory.makePrefixNode(groupWeight, prefix).build()); lpGroup.setPermission(NodeFactory.makePrefixNode(groupWeight, prefix).build());
} }
if (suffix != null && !suffix.equals("")) { if (suffix != null && !suffix.equals("")) {
lpGroup.setPermissionUnchecked(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); lpGroup.setPermission(NodeFactory.makeSuffixNode(groupWeight, suffix).build());
} }
plugin.getStorage().saveGroup(lpGroup); plugin.getStorage().saveGroup(lpGroup);
@ -176,7 +176,7 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
try { try {
for (String node : user.getOwnPermissions(null)) { for (String node : user.getOwnPermissions(null)) {
lpUser.setPermissionUnchecked(MigrationUtils.parseNode(node, true).build()); lpUser.setPermission(MigrationUtils.parseNode(node, true).build());
} }
} catch (NullPointerException ignored) { } catch (NullPointerException ignored) {
// No docs on if #getOwnPermissions(null) is ok. Should be fine though. // No docs on if #getOwnPermissions(null) is ok. Should be fine though.
@ -184,17 +184,17 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
for (String world : worlds) { for (String world : worlds) {
for (String node : user.getOwnPermissions(world)) { 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()) { 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 world : worlds) {
for (String g : user.getGroupNames(world)) { 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<Object> {
String suffix = user.getOwnSuffix(); String suffix = user.getOwnSuffix();
if (prefix != null && !prefix.equals("")) { if (prefix != null && !prefix.equals("")) {
lpUser.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); lpUser.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build());
} }
if (suffix != null && !suffix.equals("")) { 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 // Lowest rank is the highest group #logic
@ -220,9 +220,9 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
} }
if (primary != null && !primary.equalsIgnoreCase("default")) { 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.getPrimaryGroup().setStoredValue(primary);
lpUser.unsetPermissionUnchecked(NodeFactory.make("group.default")); lpUser.unsetPermission(NodeFactory.make("group.default"));
} }
plugin.getUserManager().cleanup(lpUser); plugin.getUserManager().cleanup(lpUser);

View File

@ -180,7 +180,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
} }
for (Group parent : g.getParents()) { 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 // server --> prefix afaik
@ -191,9 +191,9 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
} }
if (server != null) { 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 { } 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<Object> {
} }
if (server != null) { 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 { } 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<Object> {
String suffix = joinFuture(pm.getPlayerOwnSuffix(uuid)); String suffix = joinFuture(pm.getPlayerOwnSuffix(uuid));
if (prefix != null && !prefix.equals("")) { if (prefix != null && !prefix.equals("")) {
user.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); user.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build());
} }
if (suffix != null && !suffix.equals("")) { 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(); String primary = joinFuture(pm.getPlayerPrimaryGroup(uuid)).getName().toLowerCase();
if (!primary.equals("default")) { if (!primary.equals("default")) {
user.setPermissionUnchecked(NodeFactory.make("group." + primary)); user.setPermission(NodeFactory.make("group." + primary));
user.getPrimaryGroup().setStoredValue(primary); user.getPrimaryGroup().setStoredValue(primary);
} }
@ -316,7 +316,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
nb.setWorld(world); nb.setWorld(world);
} }
holder.setPermissionUnchecked(nb.build()); holder.setPermission(nb.build());
} }
private void applyGroup(PermissionManager pm, PermissionHolder holder, CachedGroup g, String server) { private void applyGroup(PermissionManager pm, PermissionHolder holder, CachedGroup g, String server) {
@ -338,7 +338,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
nb.setServer(server); nb.setServer(server);
} }
holder.setPermissionUnchecked(nb.build()); holder.setPermission(nb.build());
} }
@SneakyThrows @SneakyThrows

View File

@ -147,9 +147,9 @@ public class MigrationZPermissions extends SubCommand<Object> {
private void migrateEntity(PermissionHolder holder, PermissionEntity entity, List<Membership> memberships) { private void migrateEntity(PermissionHolder holder, PermissionEntity entity, List<Membership> memberships) {
for (Entry e : entity.getPermissions()) { for (Entry e : entity.getPermissions()) {
if (e.getWorld() != null && !e.getWorld().getName().equals("")) { 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 { } 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<Object> {
// entity.getMemberships() doesn't work for groups (always returns 0 records) // entity.getMemberships() doesn't work for groups (always returns 0 records)
for (Inheritance inheritance : entity.getInheritancesAsChild()) { for (Inheritance inheritance : entity.getInheritancesAsChild()) {
if (!inheritance.getParent().getName().equals(holder.getObjectName())) { 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 { } else {
for (Membership membership : memberships) { 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<Object> {
String key = metadata.getName().toLowerCase(); String key = metadata.getName().toLowerCase();
if (key.equals("prefix") || key.equals("suffix")) { 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 { } else {
holder.setPermissionUnchecked(NodeFactory.makeMetaNode(key, metadata.getStringValue()).build()); holder.setPermission(NodeFactory.makeMetaNode(key, metadata.getStringValue()).build());
} }
} }
} }

View File

@ -81,7 +81,7 @@ public class VaultChatHook extends Chat {
metaNode.setWorld(finalWorld); metaNode.setWorld(finalWorld);
} }
holder.setPermissionUnchecked(metaNode.build()); holder.setPermission(metaNode.build());
perms.save(holder); perms.save(holder);
}); });
} }
@ -111,7 +111,7 @@ public class VaultChatHook extends Chat {
chatMetaNode.setWorld(finalWorld); chatMetaNode.setWorld(finalWorld);
} }
holder.setPermissionUnchecked(chatMetaNode.build()); holder.setPermission(chatMetaNode.build());
perms.save(holder); perms.save(holder);
}); });
} }

View File

@ -30,22 +30,24 @@ import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.api.Tristate; import me.lucko.luckperms.api.Tristate;
import me.lucko.luckperms.api.caching.PermissionData; import me.lucko.luckperms.api.caching.PermissionData;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import me.lucko.luckperms.api.context.ImmutableContextSet;
import me.lucko.luckperms.bukkit.LPBukkitPlugin; import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.common.config.ConfigKeys; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.utils.ExtractedContexts; 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 net.milkbowl.vault.permission.Permission;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
/** /**
* LuckPerms Vault Permission implementation * LuckPerms Vault Permission implementation
@ -91,15 +93,16 @@ public class VaultPermissionHook extends Permission {
*/ */
private CompletableFuture<Void> add(String world, PermissionHolder holder, String permission) { private CompletableFuture<Void> add(String world, PermissionHolder holder, String permission) {
return CompletableFuture.runAsync(() -> { return CompletableFuture.runAsync(() -> {
try { DataMutateResult result;
if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) {
holder.setPermission(NodeFactory.make(permission, true, getServer(), world)); result = holder.setPermission(NodeFactory.make(permission, true, getServer(), world));
} else { } else {
holder.setPermission(NodeFactory.make(permission, true, getServer())); result = holder.setPermission(NodeFactory.make(permission, true, getServer()));
} }
if (result.asBoolean()) {
save(holder); save(holder);
} catch (ObjectAlreadyHasException ignored) {} }
}, scheduler); }, scheduler);
} }
@ -112,15 +115,16 @@ public class VaultPermissionHook extends Permission {
*/ */
private CompletableFuture<Void> remove(String world, PermissionHolder holder, String permission) { private CompletableFuture<Void> remove(String world, PermissionHolder holder, String permission) {
return CompletableFuture.runAsync(() -> { return CompletableFuture.runAsync(() -> {
try { DataMutateResult result;
if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) { if (world != null && !world.equals("") && !world.equalsIgnoreCase("global")) {
holder.unsetPermission(NodeFactory.make(permission, getServer(), world)); result = holder.unsetPermission(NodeFactory.make(permission, getServer(), world));
} else { } else {
holder.unsetPermission(NodeFactory.make(permission, getServer())); result = holder.unsetPermission(NodeFactory.make(permission, getServer()));
} }
if (result.asBoolean()) {
save(holder); save(holder);
} catch (ObjectLacksException ignored) {} }
}, scheduler); }, scheduler);
} }
@ -256,15 +260,16 @@ public class VaultPermissionHook extends Permission {
String w = world; String w = world;
scheduler.execute(() -> { scheduler.execute(() -> {
try { DataMutateResult result;
if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) {
user.setInheritGroup(group, getServer(), w); result = user.setInheritGroup(group, ImmutableContextSet.of("server", getServer(), "world", w));
} else { } else {
user.setInheritGroup(group, getServer()); result = user.setInheritGroup(group, ImmutableContextSet.singleton("server", getServer()));
} }
if (result.asBoolean()) {
save(user); save(user);
} catch (ObjectAlreadyHasException ignored) {} }
}); });
return true; return true;
} }
@ -282,15 +287,16 @@ public class VaultPermissionHook extends Permission {
String w = world; String w = world;
scheduler.execute(() -> { scheduler.execute(() -> {
try { DataMutateResult result;
if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) { if (w != null && !w.equals("") && !w.equalsIgnoreCase("global")) {
user.unsetInheritGroup(group, getServer(), w); result = user.unsetInheritGroup(group, ImmutableContextSet.of("server", getServer(), "world", w));
} else { } else {
user.unsetInheritGroup(group, getServer()); result = user.unsetInheritGroup(group, ImmutableContextSet.singleton("server", getServer()));
} }
if (result.asBoolean()) {
save(user); save(user);
} catch (ObjectLacksException ignored) {} }
}); });
return true; return true;
} }
@ -367,7 +373,15 @@ public class VaultPermissionHook extends Permission {
} }
if (isPgoCheckMemberOf()) { if (isPgoCheckMemberOf()) {
if (!user.getLocalGroups(getServer(), world, isIncludeGlobal()).contains(group.toLowerCase())) { String finalWorld = world;
List<String> 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; continue;
} }
} }

View File

@ -64,7 +64,7 @@ public class BungeeSenderFactory extends SenderFactory<CommandSender> {
@Override @Override
protected void sendMessage(CommandSender sender, FancyMessage message) { protected void sendMessage(CommandSender sender, FancyMessage message) {
try { try {
sender.sendMessage(ComponentSerializer.parse(message.toJSONString())); sender.sendMessage(ComponentSerializer.parse(message.exportToJson()));
} catch (Exception e) { } catch (Exception e) {
sendMessage(sender, message.toOldMessageFormat()); sendMessage(sender, message.toOldMessageFormat());
} }

View File

@ -88,26 +88,26 @@ public class MigrationBungeePerms extends SubCommand<Object> {
// Migrate global perms // Migrate global perms
for (String perm : g.getPerms()) { for (String perm : g.getPerms()) {
group.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).build()); group.setPermission(MigrationUtils.parseNode(perm, true).build());
} }
// Migrate per-server perms // Migrate per-server perms
for (Map.Entry<String, Server> e : g.getServers().entrySet()) { for (Map.Entry<String, Server> e : g.getServers().entrySet()) {
for (String perm : e.getValue().getPerms()) { 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 // Migrate per-world perms
for (Map.Entry<String, World> we : e.getValue().getWorlds().entrySet()) { for (Map.Entry<String, World> we : e.getValue().getWorlds().entrySet()) {
for (String perm : we.getValue().getPerms()) { 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 // Migrate any parent groups
for (String inherit : g.getInheritances()) { 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 // Migrate prefix and suffix
@ -115,10 +115,10 @@ public class MigrationBungeePerms extends SubCommand<Object> {
String suffix = g.getSuffix(); String suffix = g.getSuffix();
if (prefix != null && !prefix.equals("")) { if (prefix != null && !prefix.equals("")) {
group.setPermissionUnchecked(NodeFactory.makePrefixNode(groupWeight, prefix).build()); group.setPermission(NodeFactory.makePrefixNode(groupWeight, prefix).build());
} }
if (suffix != null && !suffix.equals("")) { if (suffix != null && !suffix.equals("")) {
group.setPermissionUnchecked(NodeFactory.makeSuffixNode(groupWeight, suffix).build()); group.setPermission(NodeFactory.makeSuffixNode(groupWeight, suffix).build());
} }
plugin.getStorage().saveGroup(group); plugin.getStorage().saveGroup(group);
@ -145,26 +145,26 @@ public class MigrationBungeePerms extends SubCommand<Object> {
// Migrate global perms // Migrate global perms
for (String perm : u.getPerms()) { for (String perm : u.getPerms()) {
user.setPermissionUnchecked(MigrationUtils.parseNode(perm, true).build()); user.setPermission(MigrationUtils.parseNode(perm, true).build());
} }
// Migrate per-server perms // Migrate per-server perms
for (Map.Entry<String, Server> e : u.getServers().entrySet()) { for (Map.Entry<String, Server> e : u.getServers().entrySet()) {
for (String perm : e.getValue().getPerms()) { 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 // Migrate per-world perms
for (Map.Entry<String, World> we : e.getValue().getWorlds().entrySet()) { for (Map.Entry<String, World> we : e.getValue().getWorlds().entrySet()) {
for (String perm : we.getValue().getPerms()) { 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 // Migrate groups
for (String group : u.getGroupsString()) { for (String group : u.getGroupsString()) {
user.setPermissionUnchecked(NodeFactory.make("group." + MigrationUtils.standardizeName(group))); user.setPermission(NodeFactory.make("group." + MigrationUtils.standardizeName(group)));
} }
// Migrate prefix & suffix // Migrate prefix & suffix
@ -172,10 +172,10 @@ public class MigrationBungeePerms extends SubCommand<Object> {
String suffix = u.getSuffix(); String suffix = u.getSuffix();
if (prefix != null && !prefix.equals("")) { if (prefix != null && !prefix.equals("")) {
user.setPermissionUnchecked(NodeFactory.makePrefixNode(maxWeight, prefix).build()); user.setPermission(NodeFactory.makePrefixNode(maxWeight, prefix).build());
} }
if (suffix != null && !suffix.equals("")) { if (suffix != null && !suffix.equals("")) {
user.setPermissionUnchecked(NodeFactory.makeSuffixNode(maxWeight, suffix).build()); user.setPermission(NodeFactory.makeSuffixNode(maxWeight, suffix).build());
} }
plugin.getStorage().saveUser(user); plugin.getStorage().saveUser(user);

View File

@ -38,7 +38,7 @@
<dependency> <dependency>
<groupId>io.github.mkremins</groupId> <groupId>io.github.mkremins</groupId>
<artifactId>fanciful</artifactId> <artifactId>fanciful</artifactId>
<version>1.2.0</version> <version>1.2.5</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- MySQL --> <!-- MySQL -->

View File

@ -42,7 +42,6 @@ import me.lucko.luckperms.api.context.ContextCalculator;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import me.lucko.luckperms.common.api.delegates.NodeFactoryDelegate; import me.lucko.luckperms.common.api.delegates.NodeFactoryDelegate;
import me.lucko.luckperms.common.api.delegates.UserDelegate; import me.lucko.luckperms.common.api.delegates.UserDelegate;
import me.lucko.luckperms.common.core.NodeBuilder;
import me.lucko.luckperms.common.core.UserIdentifier; import me.lucko.luckperms.common.core.UserIdentifier;
import me.lucko.luckperms.common.event.EventFactory; import me.lucko.luckperms.common.event.EventFactory;
import me.lucko.luckperms.common.event.LuckPermsEventBus; import me.lucko.luckperms.common.event.LuckPermsEventBus;
@ -153,8 +152,7 @@ public class ApiProvider implements LuckPermsApi {
@Override @Override
public void cleanupUser(@NonNull User user) { public void cleanupUser(@NonNull User user) {
ApiUtils.checkUser(user); plugin.getUserManager().cleanup(UserDelegate.cast(user));
plugin.getUserManager().cleanup(((UserDelegate) user).getMaster());
} }
@Override @Override
@ -206,7 +204,7 @@ public class ApiProvider implements LuckPermsApi {
@Override @Override
public Node.Builder buildNode(@NonNull String permission) throws IllegalArgumentException { public Node.Builder buildNode(@NonNull String permission) throws IllegalArgumentException {
return new NodeBuilder(permission); return me.lucko.luckperms.common.core.NodeFactory.newBuilder(permission);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -217,8 +215,7 @@ public class ApiProvider implements LuckPermsApi {
@Override @Override
public Optional<Contexts> getContextForUser(User user) { public Optional<Contexts> getContextForUser(User user) {
ApiUtils.checkUser(user); return Optional.ofNullable(plugin.getContextForUser(UserDelegate.cast(user)));
return Optional.ofNullable(plugin.getContextForUser(((UserDelegate) user).getMaster()));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -26,29 +26,11 @@ import lombok.experimental.UtilityClass;
import com.google.common.base.Preconditions; 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; import me.lucko.luckperms.common.utils.ArgumentChecker;
@UtilityClass @UtilityClass
public class ApiUtils { 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) { public static String checkUsername(String s) {
Preconditions.checkArgument( Preconditions.checkArgument(
!ArgumentChecker.checkUsername(s), !ArgumentChecker.checkUsername(s),

View File

@ -26,147 +26,152 @@ import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import com.google.common.base.Preconditions;
import me.lucko.luckperms.api.Group; 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.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.OptionalInt; 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; import static me.lucko.luckperms.common.api.ApiUtils.checkTime;
/** /**
* Provides a link between {@link Group} and {@link me.lucko.luckperms.common.core.model.Group} * Provides a link between {@link Group} and {@link me.lucko.luckperms.common.core.model.Group}
*/ */
public final class GroupDelegate extends PermissionHolderDelegate implements 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) @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) { public GroupDelegate(@NonNull me.lucko.luckperms.common.core.model.Group handle) {
super(master); super(handle);
this.master = master; this.handle = handle;
} }
@Override @Override
public String getName() { public String getName() {
return master.getName(); return handle.getName();
} }
@Override @Override
public boolean inheritsGroup(@NonNull Group group) { public boolean inheritsGroup(@NonNull Group group) {
checkGroup(group); return handle.inheritsGroup(cast(group));
return master.inheritsGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public boolean inheritsGroup(@NonNull Group group, @NonNull String server) { public boolean inheritsGroup(@NonNull Group group, @NonNull String server) {
checkGroup(group); return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server);
return master.inheritsGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public boolean inheritsGroup(@NonNull Group group, @NonNull String server, @NonNull String world) { public boolean inheritsGroup(@NonNull Group group, @NonNull String server, @NonNull String world) {
checkGroup(group); return handle.inheritsGroup(cast(group), server, world);
return master.inheritsGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void setInheritGroup(@NonNull Group group) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void setInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group), server)).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group), server, world)).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void setInheritGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group), checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), checkTime(expireAt));
} }
@Override @Override
public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group), server, checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, checkTime(expireAt));
} }
@Override @Override
public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { public void setInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(cast(group), server, world, checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world, checkTime(expireAt));
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group))).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group), temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), temporary);
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group), server)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group), server, world)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group), server, temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, temporary);
} }
@Override @Override
public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { public void unsetInheritGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(cast(group), server, world, temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world, temporary);
} }
@Override @Override
public void clearNodes() { public void clearNodes() {
master.clearNodes(); handle.clearNodes();
} }
@Override @Override
public List<String> getGroupNames() { public List<String> getGroupNames() {
return master.getGroupNames(); return handle.mergePermissionsToList().stream()
.filter(Node::isGroupNode)
.map(Node::getGroupName)
.collect(Collectors.toList());
} }
@Override @Override
public List<String> getLocalGroups(@NonNull String server, @NonNull String world) { public List<String> 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 @Override
public OptionalInt getWeight() { public OptionalInt getWeight() {
return master.getWeight(); return handle.getWeight();
} }
@Override @Override
public List<String> getLocalGroups(@NonNull String server) { public List<String> 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) { public boolean equals(Object o) {

View File

@ -33,6 +33,7 @@ import me.lucko.luckperms.api.LocalizedNode;
import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.api.PermissionHolder; import me.lucko.luckperms.api.PermissionHolder;
import me.lucko.luckperms.api.Tristate; 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.core.NodeFactory;
import me.lucko.luckperms.common.utils.ExtractedContexts; import me.lucko.luckperms.common.utils.ExtractedContexts;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
@ -166,82 +167,82 @@ public class PermissionHolderDelegate implements PermissionHolder {
@Override @Override
public void setPermission(@NonNull Node node) throws ObjectAlreadyHasException { public void setPermission(@NonNull Node node) throws ObjectAlreadyHasException {
master.setPermission(node); master.setPermission(node).throwException();
} }
@Override @Override
public void setTransientPermission(@NonNull Node node) throws ObjectAlreadyHasException { public void setTransientPermission(@NonNull Node node) throws ObjectAlreadyHasException {
master.setTransientPermission(node); master.setTransientPermission(node).throwException();
} }
@Override @Override
public void setPermission(@NonNull String node, @NonNull boolean value) throws ObjectAlreadyHasException { 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 @Override
public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server) throws ObjectAlreadyHasException { 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 @Override
public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { 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 @Override
public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull long expireAt) throws ObjectAlreadyHasException { 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 @Override
public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { 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 @Override
public void setPermission(@NonNull String node, @NonNull boolean value, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { 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 @Override
public void unsetPermission(@NonNull Node node) throws ObjectLacksException { public void unsetPermission(@NonNull Node node) throws ObjectLacksException {
master.unsetPermission(node); master.unsetPermission(node).throwException();
} }
@Override @Override
public void unsetTransientPermission(@NonNull Node node) throws ObjectLacksException { public void unsetTransientPermission(@NonNull Node node) throws ObjectLacksException {
master.unsetTransientPermission(node); master.unsetTransientPermission(node).throwException();
} }
@Override @Override
public void unsetPermission(@NonNull String node, @NonNull boolean temporary) throws ObjectLacksException { 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 @Override
public void unsetPermission(@NonNull String node) throws ObjectLacksException { public void unsetPermission(@NonNull String node) throws ObjectLacksException {
master.unsetPermission(NodeFactory.make(node)); master.unsetPermission(NodeFactory.make(node)).throwException();
} }
@Override @Override
public void unsetPermission(@NonNull String node, @NonNull String server) throws ObjectLacksException { 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 @Override
public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull String world) throws ObjectLacksException { 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 @Override
public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { 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 @Override
public void unsetPermission(@NonNull String node, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { 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 @Override
@ -251,12 +252,25 @@ public class PermissionHolderDelegate implements PermissionHolder {
@Override @Override
public void clearNodes(String server) { public void clearNodes(String server) {
master.clearNodes(server); MutableContextSet set = new MutableContextSet();
if (server != null) {
set.add("server", server);
}
master.clearNodes(set);
} }
@Override @Override
public void clearNodes(String server, String world) { 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 @Override
@ -266,12 +280,25 @@ public class PermissionHolderDelegate implements PermissionHolder {
@Override @Override
public void clearParents(String server) { 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 @Override
public void clearParents(String server, String world) { 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 @Override
@ -281,17 +308,38 @@ public class PermissionHolderDelegate implements PermissionHolder {
@Override @Override
public void clearMeta(String server) { public void clearMeta(String server) {
master.clearMeta(server); MutableContextSet set = new MutableContextSet();
if (server != null) {
set.add("server", server);
}
master.clearMeta(set);
} }
@Override @Override
public void clearMeta(String server, String world) { 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 @Override
public void clearMetaKeys(String key, String server, String world, boolean temporary) { 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 @Override

View File

@ -43,10 +43,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; 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.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; import static me.lucko.luckperms.common.api.ApiUtils.checkUsername;
/** /**
@ -94,8 +91,7 @@ public class StorageDelegate implements Storage {
@Override @Override
public CompletableFuture<Boolean> saveUser(User user) { public CompletableFuture<Boolean> saveUser(User user) {
checkUser(user); return master.force().saveUser(UserDelegate.cast(user));
return master.force().saveUser(((UserDelegate) user).getMaster());
} }
@Override @Override
@ -130,17 +126,15 @@ public class StorageDelegate implements Storage {
@Override @Override
public CompletableFuture<Boolean> saveGroup(Group group) { public CompletableFuture<Boolean> saveGroup(Group group) {
checkGroup(group); return master.force().saveGroup(GroupDelegate.cast(group));
return master.force().saveGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public CompletableFuture<Boolean> deleteGroup(Group group) { public CompletableFuture<Boolean> deleteGroup(Group group) {
checkGroup(group);
if (group.getName().equalsIgnoreCase(plugin.getConfiguration().get(ConfigKeys.DEFAULT_GROUP_NAME))) { if (group.getName().equalsIgnoreCase(plugin.getConfiguration().get(ConfigKeys.DEFAULT_GROUP_NAME))) {
throw new IllegalArgumentException("Cannot delete the default group."); 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 @Override
@ -165,14 +159,12 @@ public class StorageDelegate implements Storage {
@Override @Override
public CompletableFuture<Boolean> saveTrack(Track track) { public CompletableFuture<Boolean> saveTrack(Track track) {
checkTrack(track); return master.force().saveTrack(TrackDelegate.cast(track));
return master.force().saveTrack(((TrackDelegate) track).getMaster());
} }
@Override @Override
public CompletableFuture<Boolean> deleteTrack(Track track) { public CompletableFuture<Boolean> deleteTrack(Track track) {
checkTrack(track); return master.force().deleteTrack(TrackDelegate.cast(track), DeletionCause.API);
return master.force().deleteTrack(((TrackDelegate) track).getMaster(), DeletionCause.API);
} }
@Override @Override

View File

@ -27,6 +27,8 @@ import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import com.google.common.base.Preconditions;
import me.lucko.luckperms.api.Group; import me.lucko.luckperms.api.Group;
import me.lucko.luckperms.api.Track; import me.lucko.luckperms.api.Track;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
@ -34,81 +36,77 @@ import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; 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} * Provides a link between {@link Track} and {@link me.lucko.luckperms.common.core.model.Track}
*/ */
@AllArgsConstructor @AllArgsConstructor
public final class TrackDelegate implements Track { 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) @Getter(AccessLevel.PACKAGE)
private final me.lucko.luckperms.common.core.model.Track master; private final me.lucko.luckperms.common.core.model.Track handle;
@Override @Override
public String getName() { public String getName() {
return master.getName(); return handle.getName();
} }
@Override @Override
public List<String> getGroups() { public List<String> getGroups() {
return master.getGroups(); return handle.getGroups();
} }
@Override @Override
public int getSize() { public int getSize() {
return master.getSize(); return handle.getSize();
} }
@Override @Override
public String getNext(@NonNull Group current) throws ObjectLacksException { public String getNext(@NonNull Group current) throws ObjectLacksException {
checkGroup(current); return handle.getNext(GroupDelegate.cast(current));
return master.getNext(((GroupDelegate) current).getMaster());
} }
@Override @Override
public String getPrevious(@NonNull Group current) throws ObjectLacksException { public String getPrevious(@NonNull Group current) throws ObjectLacksException {
checkGroup(current); return handle.getPrevious(GroupDelegate.cast(current));
return master.getPrevious(((GroupDelegate) current).getMaster());
} }
@Override @Override
public void appendGroup(@NonNull Group group) throws ObjectAlreadyHasException { public void appendGroup(@NonNull Group group) throws ObjectAlreadyHasException {
checkGroup(group); handle.appendGroup(GroupDelegate.cast(group));
master.appendGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void insertGroup(@NonNull Group group, @NonNull int position) throws ObjectAlreadyHasException, IndexOutOfBoundsException { public void insertGroup(@NonNull Group group, @NonNull int position) throws ObjectAlreadyHasException, IndexOutOfBoundsException {
checkGroup(group); handle.insertGroup(GroupDelegate.cast(group), position);
master.insertGroup(((GroupDelegate) group).getMaster(), position);
} }
@Override @Override
public void removeGroup(@NonNull Group group) throws ObjectLacksException { public void removeGroup(@NonNull Group group) throws ObjectLacksException {
checkGroup(group); handle.removeGroup(GroupDelegate.cast(group));
master.removeGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void removeGroup(@NonNull String group) throws ObjectLacksException { public void removeGroup(@NonNull String group) throws ObjectLacksException {
master.removeGroup(group); handle.removeGroup(group);
} }
@Override @Override
public boolean containsGroup(@NonNull Group group) { public boolean containsGroup(@NonNull Group group) {
checkGroup(group); return handle.containsGroup(GroupDelegate.cast(group));
return master.containsGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public boolean containsGroup(@NonNull String group) { public boolean containsGroup(@NonNull String group) {
return master.containsGroup(group); return handle.containsGroup(group);
} }
@Override @Override
public void clearGroups() { public void clearGroups() {
master.clearGroups(); handle.clearGroups();
} }
public boolean equals(Object o) { public boolean equals(Object o) {

View File

@ -25,45 +25,53 @@ package me.lucko.luckperms.common.api.delegates;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import com.google.common.base.Preconditions;
import me.lucko.luckperms.api.Group; import me.lucko.luckperms.api.Group;
import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.api.User; import me.lucko.luckperms.api.User;
import me.lucko.luckperms.api.caching.UserData; 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.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; 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; import static me.lucko.luckperms.common.api.ApiUtils.checkTime;
/** /**
* Provides a link between {@link User} and {@link me.lucko.luckperms.common.core.model.User} * Provides a link between {@link User} and {@link me.lucko.luckperms.common.core.model.User}
*/ */
public final class UserDelegate extends PermissionHolderDelegate implements 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 @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) { public UserDelegate(@NonNull me.lucko.luckperms.common.core.model.User handle) {
super(master); super(handle);
this.master = master; this.handle = handle;
} }
@Override @Override
public UUID getUuid() { public UUID getUuid() {
return master.getUuid(); return handle.getUuid();
} }
@Override @Override
public String getName() { public String getName() {
return master.getName(); return handle.getName();
} }
@Override @Override
public String getPrimaryGroup() { public String getPrimaryGroup() {
return master.getPrimaryGroup().getValue(); return handle.getPrimaryGroup().getValue();
} }
@Override @Override
@ -76,132 +84,129 @@ public final class UserDelegate extends PermissionHolderDelegate implements User
throw new IllegalStateException("User is not a member of that group."); throw new IllegalStateException("User is not a member of that group.");
} }
master.getPrimaryGroup().setStoredValue(s.toLowerCase()); handle.getPrimaryGroup().setStoredValue(s.toLowerCase());
} }
@Override @Override
public void refreshPermissions() { public void refreshPermissions() {
master.getRefreshBuffer().requestDirectly(); handle.getRefreshBuffer().requestDirectly();
} }
@Override @Override
public Optional<UserData> getUserDataCache() { public Optional<UserData> getUserDataCache() {
return Optional.ofNullable(master.getUserData()); return Optional.ofNullable(handle.getUserData());
} }
@Override @Override
public void setupDataCache() { public void setupDataCache() {
master.setupData(false); handle.setupData(false);
} }
@Override @Override
public boolean isInGroup(@NonNull Group group) { public boolean isInGroup(@NonNull Group group) {
checkGroup(group); return handle.inheritsGroup(GroupDelegate.cast(group));
return master.inheritsGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public boolean isInGroup(@NonNull Group group, @NonNull String server) { public boolean isInGroup(@NonNull Group group, @NonNull String server) {
checkGroup(group); return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server);
return master.inheritsGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public boolean isInGroup(@NonNull Group group, @NonNull String server, @NonNull String world) { public boolean isInGroup(@NonNull Group group, @NonNull String server, @NonNull String world) {
checkGroup(group); return handle.inheritsGroup(((GroupDelegate) group).getHandle(), server, world);
return master.inheritsGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void addGroup(@NonNull Group group) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void addGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group, @NonNull String server) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server)).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, world)).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void addGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), checkTime(expireAt));
} }
@Override @Override
public void addGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group, @NonNull String server, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, checkTime(expireAt));
} }
@Override @Override
public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException { public void addGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull long expireAt) throws ObjectAlreadyHasException {
checkGroup(group); handle.setPermission(NodeFactory.make(GroupDelegate.cast(group), server, world, checkTime(expireAt))).throwException();
master.setInheritGroup(((GroupDelegate) group).getMaster(), server, world, checkTime(expireAt));
} }
@Override @Override
public void removeGroup(@NonNull Group group) throws ObjectLacksException { public void removeGroup(@NonNull Group group) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group))).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster());
} }
@Override @Override
public void removeGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException { public void removeGroup(@NonNull Group group, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), temporary);
} }
@Override @Override
public void removeGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException { public void removeGroup(@NonNull Group group, @NonNull String server) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server);
} }
@Override @Override
public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException { public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, world)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world);
} }
@Override @Override
public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException { public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, temporary);
} }
@Override @Override
public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException { public void removeGroup(@NonNull Group group, @NonNull String server, @NonNull String world, @NonNull boolean temporary) throws ObjectLacksException {
checkGroup(group); handle.unsetPermission(NodeFactory.make(GroupDelegate.cast(group), server, world, temporary)).throwException();
master.unsetInheritGroup(((GroupDelegate) group).getMaster(), server, world, temporary);
} }
@Override @Override
public void clearNodes() { public void clearNodes() {
master.clearNodes(); handle.clearNodes();
} }
@Override @Override
public List<String> getGroupNames() { public List<String> getGroupNames() {
return master.getGroupNames(); return handle.mergePermissionsToList().stream()
.filter(Node::isGroupNode)
.map(Node::getGroupName)
.collect(Collectors.toList());
} }
@Override @Override
public List<String> getLocalGroups(@NonNull String server, @NonNull String world) { public List<String> 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 @Override
public List<String> getLocalGroups(@NonNull String server) { public List<String> 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) { public boolean equals(Object o) {

View File

@ -117,7 +117,15 @@ public class CommandManager {
* @param args the arguments provided * @param args the arguments provided
*/ */
public Future<CommandResult> onCommand(Sender sender, String label, List<String> args) { public Future<CommandResult> onCommand(Sender sender, String label, List<String> 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") @SuppressWarnings("unchecked")

View File

@ -36,14 +36,14 @@ public class CommandMeta<T extends PermissionHolder> extends SharedMainCommand<T
.add(new MetaUnset()) .add(new MetaUnset())
.add(new MetaSetTemp()) .add(new MetaSetTemp())
.add(new MetaUnsetTemp()) .add(new MetaUnsetTemp())
.add(new MetaAddPrefix()) .add(new MetaAddChatMeta(true))
.add(new MetaAddSuffix()) .add(new MetaAddChatMeta(false))
.add(new MetaRemovePrefix()) .add(new MetaRemoveChatMeta(true))
.add(new MetaRemoveSuffix()) .add(new MetaRemoveChatMeta(false))
.add(new MetaAddTempPrefix()) .add(new MetaAddTempChatMeta(true))
.add(new MetaAddTempSuffix()) .add(new MetaAddTempChatMeta(false))
.add(new MetaRemoveTempPrefix()) .add(new MetaRemoveTempChatMeta(true))
.add(new MetaRemoveTempSuffix()) .add(new MetaRemoveTempChatMeta(false))
.add(new MetaClear()) .add(new MetaClear())
.build()); .build());
} }

View File

@ -22,73 +22,64 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaAddPrefix extends SharedSubCommand { public class MetaAddChatMeta extends SharedSubCommand {
public MetaAddPrefix() { private static final Function<Boolean, String> DESCRIPTOR = b -> b ? "prefix" : "suffix";
super("addprefix", "Adds a prefix", Permission.USER_META_ADDPREFIX, Permission.GROUP_META_ADDPREFIX, private final boolean isPrefix;
Predicates.notInRange(2, 4),
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.list(
Arg.create("priority", true, "the priority to add the prefix at"), Arg.create("priority", true, "the priority to add the " + DESCRIPTOR.apply(isPrefix) + " at"),
Arg.create("prefix", true, "the prefix string"), Arg.create(DESCRIPTOR.apply(isPrefix), true, "the " + DESCRIPTOR.apply(isPrefix) + " string"),
Arg.create("server", false, "the server to add the prefix on"), Arg.create("context...", false, "the contexts to add the " + DESCRIPTOR.apply(isPrefix) + " in")
Arg.create("world", false, "the world to add the prefix on")
) )
); );
this.isPrefix = isPrefix;
} }
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int priority = ArgumentUtils.handlePriority(0, args); int priority = ArgumentUtils.handlePriority(0, args);
String prefix = ArgumentUtils.handleString(1, args); String meta = ArgumentUtils.handleString(1, args);
String server = ArgumentUtils.handleServer(2, args); MutableContextSet context = ArgumentUtils.handleContext(2, args);
String world = ArgumentUtils.handleWorld(3, args);
final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); DataMutateResult result = holder.setPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, meta).withExtraContext(context).build());
if (result.asBoolean()) {
try { Message.ADD_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), meta, priority, Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) 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); .build().submit(plugin, sender);
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) { Message.ALREADY_HAS_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix));
Message.ALREADY_HAS_PREFIX.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
} }

View File

@ -22,85 +22,75 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.TemporaryModifier;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaAddTempPrefix extends SharedSubCommand { public class MetaAddTempChatMeta extends SharedSubCommand {
public MetaAddTempPrefix() { private static final Function<Boolean, String> DESCRIPTOR = b -> b ? "prefix" : "suffix";
super("addtempprefix", "Adds a prefix temporarily", Permission.USER_META_ADDTEMP_PREFIX, private final boolean isPrefix;
Permission.GROUP_META_ADDTEMP_PREFIX, Predicates.notInRange(3, 5),
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.list(
Arg.create("priority", true, "the priority to add the prefix at"), Arg.create("priority", true, "the priority to add the " + DESCRIPTOR.apply(isPrefix) + " at"),
Arg.create("prefix", true, "the prefix string"), Arg.create(DESCRIPTOR.apply(isPrefix), true, "the " + DESCRIPTOR.apply(isPrefix) + " string"),
Arg.create("duration", true, "the duration until the prefix expires"), Arg.create("duration", true, "the duration until the " + DESCRIPTOR.apply(isPrefix) + " expires"),
Arg.create("server", false, "the server to add the prefix on"), Arg.create("context...", false, "the contexts to add the " + DESCRIPTOR.apply(isPrefix) + " in")
Arg.create("world", false, "the world to add the prefix on")
) )
); );
this.isPrefix = isPrefix;
} }
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int priority = ArgumentUtils.handlePriority(0, args); int priority = ArgumentUtils.handlePriority(0, args);
String prefix = ArgumentUtils.handleString(1, args); String meta = ArgumentUtils.handleString(1, args);
long duration = ArgumentUtils.handleDuration(2, args); long duration = ArgumentUtils.handleDuration(2, args);
String server = ArgumentUtils.handleServer(3, args); MutableContextSet context = ArgumentUtils.handleContext(3, args);
String world = ArgumentUtils.handleWorld(4, args);
TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR);
final String node = "prefix." + priority + "." + MetaUtils.escapeCharacters(prefix); Map.Entry<DataMutateResult, Node> ret = holder.setPermission(NodeFactory.makeChatMetaNode(isPrefix, priority, meta).setExpiry(duration).withExtraContext(context).build(), modifier);
try { if (ret.getKey().asBoolean()) {
switch (ContextHelper.determine(server, world)) { duration = ret.getValue().getExpiryUnixTime();
case NONE:
duration = holder.setPermission(new NodeBuilder(node).setValue(true).setExpiry(duration).build(), modifier).getExpiryUnixTime(); Message.ADD_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), meta, meta, DateUtil.formatDateDiff(duration), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) 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); .build().submit(plugin, sender);
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) { Message.ALREADY_HAS_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix));
Message.ALREADY_HAS_PREFIX.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
} }

View File

@ -1,107 +0,0 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<String> 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;
}
}
}

View File

@ -22,13 +22,13 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
@ -41,10 +41,9 @@ import java.util.stream.Collectors;
public class MetaClear extends SharedSubCommand { public class MetaClear extends SharedSubCommand {
public MetaClear() { 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.list(
Arg.create("server", false, "the server name to filter by"), Arg.create("context...", false, "the contexts to filter by")
Arg.create("world", false, "the world name to filter by")
) )
); );
} }
@ -53,19 +52,12 @@ public class MetaClear extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int before = holder.getNodes().size(); int before = holder.getNodes().size();
String server = ArgumentUtils.handleServer(0, args); MutableContextSet context = ArgumentUtils.handleContext(0, args);
String world = ArgumentUtils.handleWorld(1, args);
switch (ContextHelper.determine(server, world)) { if (context.isEmpty()) {
case NONE:
holder.clearMeta(); holder.clearMeta();
break; } else {
case SERVER: holder.clearMeta(context);
holder.clearMeta(server);
break;
case SERVER_AND_WORLD:
holder.clearMeta(server, world);
break;
} }
int changed = before - holder.getNodes().size(); int changed = before - holder.getNodes().size();

View File

@ -28,6 +28,7 @@ import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; 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.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
@ -55,8 +56,8 @@ public class MetaInfo extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
SortedSet<Map.Entry<Integer, LocalizedNode>> prefixes = new TreeSet<>(Util.META_COMPARATOR.reversed()); SortedSet<Map.Entry<Integer, LocalizedNode>> prefixes = new TreeSet<>(MetaComparator.INSTANCE.reversed());
SortedSet<Map.Entry<Integer, LocalizedNode>> suffixes = new TreeSet<>(Util.META_COMPARATOR.reversed()); SortedSet<Map.Entry<Integer, LocalizedNode>> suffixes = new TreeSet<>(MetaComparator.INSTANCE.reversed());
Set<LocalizedNode> meta = new HashSet<>(); Set<LocalizedNode> meta = new HashSet<>();
// Collect data // Collect data
@ -81,7 +82,7 @@ public class MetaInfo extends SharedSubCommand {
for (Map.Entry<Integer, LocalizedNode> e : prefixes) { for (Map.Entry<Integer, LocalizedNode> e : prefixes) {
String location = processLocation(e.getValue(), holder); String location = processLocation(e.getValue(), holder);
if (e.getValue().isServerSpecific() || e.getValue().isWorldSpecific() || !e.getValue().getContexts().isEmpty()) { 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); Message.CHAT_META_ENTRY_WITH_CONTEXT.send(sender, e.getKey(), e.getValue().getPrefix().getValue(), location, context);
} else { } else {
Message.CHAT_META_ENTRY.send(sender, e.getKey(), e.getValue().getPrefix().getValue(), location); 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<Integer, LocalizedNode> e : suffixes) { for (Map.Entry<Integer, LocalizedNode> e : suffixes) {
String location = processLocation(e.getValue(), holder); String location = processLocation(e.getValue(), holder);
if (e.getValue().isServerSpecific() || e.getValue().isWorldSpecific() || !e.getValue().getContexts().isEmpty()) { 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); Message.CHAT_META_ENTRY_WITH_CONTEXT.send(sender, e.getKey(), e.getValue().getSuffix().getValue(), location, context);
} else { } else {
Message.CHAT_META_ENTRY.send(sender, e.getKey(), e.getValue().getSuffix().getValue(), location); 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) { for (LocalizedNode m : meta) {
String location = processLocation(m, holder); String location = processLocation(m, holder);
if (m.isServerSpecific() || m.isWorldSpecific() || !m.getContexts().isEmpty()) { 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); Message.META_ENTRY_WITH_CONTEXT.send(sender, m.getMeta().getKey(), m.getMeta().getValue(), location, context);
} else { } else {
Message.META_ENTRY.send(sender, m.getMeta().getKey(), m.getMeta().getValue(), location); Message.META_ENTRY.send(sender, m.getMeta().getKey(), m.getMeta().getValue(), location);

View File

@ -22,73 +22,79 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaAddSuffix extends SharedSubCommand { public class MetaRemoveChatMeta extends SharedSubCommand {
public MetaAddSuffix() { private static final Function<Boolean, String> DESCRIPTOR = b -> b ? "prefix" : "suffix";
super("addsuffix", "Adds a suffix", Permission.USER_META_ADDSUFFIX, Permission.GROUP_META_ADDSUFFIX, private final boolean isPrefix;
Predicates.notInRange(2, 4),
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.list(
Arg.create("priority", true, "the priority to add the suffix at"), Arg.create("priority", true, "the priority to remove the " + DESCRIPTOR.apply(isPrefix) + " at"),
Arg.create("suffix", true, "the suffix string"), Arg.create(DESCRIPTOR.apply(isPrefix), false, "the " + DESCRIPTOR.apply(isPrefix) + " string"),
Arg.create("server", false, "the server to add the suffix on"), Arg.create("server", false, "the server to remove the " + DESCRIPTOR.apply(isPrefix) + " on"),
Arg.create("world", false, "the world to add the suffix on") Arg.create("world", false, "the world to remove the " + DESCRIPTOR.apply(isPrefix) + " on")
) )
); );
this.isPrefix = isPrefix;
} }
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int priority = ArgumentUtils.handlePriority(0, args); int priority = ArgumentUtils.handlePriority(0, args);
String suffix = ArgumentUtils.handleString(1, args); String prefix = ArgumentUtils.handleStringOrElse(1, args, "null");
String server = ArgumentUtils.handleServer(2, args); MutableContextSet context = ArgumentUtils.handleContext(2, args);
String world = ArgumentUtils.handleWorld(3, args);
final String node = "suffix." + priority + "." + MetaUtils.escapeCharacters(suffix); // Handle bulk removal
if (prefix.equalsIgnoreCase("null")) {
try { holder.removeIf(n ->
switch (ContextHelper.determine(server, world)) { n.isPrefix() &&
case NONE: n.getPrefix().getKey() == priority &&
holder.setPermission(NodeFactory.make(node, true)); !n.isTemporary() &&
Message.ADDSUFFIX_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority); n.getFullContexts().makeImmutable().equals(context.makeImmutable())
break; );
case SERVER: Message.BULK_REMOVE_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), priority, Util.contextSetToString(context));
holder.setPermission(NodeFactory.make(node, true, server)); save(holder, sender, plugin);
Message.ADDSUFFIX_SERVER_SUCCESS.send(sender, holder.getFriendlyName(), suffix, priority, server); return CommandResult.SUCCESS;
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) 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); .build().submit(plugin, sender);
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) { Message.DOES_NOT_HAVE_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix));
Message.ALREADY_HAS_SUFFIX.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
} }

View File

@ -1,129 +0,0 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<String> 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<Node> 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;
}
}
}

View File

@ -22,107 +22,79 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.api.Node;
import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaRemovePrefix extends SharedSubCommand { public class MetaRemoveTempChatMeta extends SharedSubCommand {
public MetaRemovePrefix() { private static final Function<Boolean, String> DESCRIPTOR = b -> b ? "prefix" : "suffix";
super("removeprefix", "Removes a prefix", Permission.USER_META_REMOVEPREFIX, Permission.GROUP_META_REMOVEPREFIX, private final boolean isPrefix;
Predicates.notInRange(1, 4),
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.list(
Arg.create("priority", true, "the priority to remove the prefix at"), Arg.create("priority", true, "the priority to remove the " + DESCRIPTOR.apply(isPrefix) + " at"),
Arg.create("prefix", false, "the prefix string"), Arg.create(DESCRIPTOR.apply(isPrefix), false, "the " + DESCRIPTOR.apply(isPrefix) + " string"),
Arg.create("server", false, "the server to remove the prefix on"), Arg.create("server", false, "the server to remove the " + DESCRIPTOR.apply(isPrefix) + " on"),
Arg.create("world", false, "the world to remove the prefix on") Arg.create("world", false, "the world to remove the " + DESCRIPTOR.apply(isPrefix) + " on")
) )
); );
this.isPrefix = isPrefix;
} }
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int priority = ArgumentUtils.handlePriority(0, args); int priority = ArgumentUtils.handlePriority(0, args);
String prefix = ArgumentUtils.handleStringOrElse(1, args, "null"); String prefix = ArgumentUtils.handleStringOrElse(1, args, "null");
String server = ArgumentUtils.handleServer(2, args); MutableContextSet context = ArgumentUtils.handleContext(2, args);
String world = ArgumentUtils.handleWorld(3, args);
// Handle bulk removal // Handle bulk removal
if (prefix.equalsIgnoreCase("null")) { if (prefix.equalsIgnoreCase("null")) {
List<Node> toRemove = new ArrayList<>(); holder.removeIf(n ->
for (Node node : holder.getNodes().values()) { n.isPrefix() &&
if (!node.isPrefix()) continue; n.getPrefix().getKey() == priority &&
if (node.getPrefix().getKey() != priority) continue; !n.isPermanent() &&
if (node.isTemporary()) continue; n.getFullContexts().makeImmutable().equals(context.makeImmutable())
);
if (node.getServer().isPresent()) { Message.BULK_REMOVE_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), priority, Util.contextSetToString(context));
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); save(holder, sender, plugin);
return CommandResult.SUCCESS; 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 { if (result.asBoolean()) {
switch (ContextHelper.determine(server, world)) { Message.REMOVE_TEMP_CHATMETA_SUCCESS.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix), prefix, priority, Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) 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); .build().submit(plugin, sender);
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectLacksException e) { Message.DOES_NOT_HAVE_CHAT_META.send(sender, holder.getFriendlyName(), DESCRIPTOR.apply(isPrefix));
Message.DOES_NOT_HAVE_PREFIX.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
} }

View File

@ -1,129 +0,0 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<String> 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<Node> 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;
}
}
}

View File

@ -1,129 +0,0 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<String> 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<Node> 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;
}
}
}

View File

@ -23,13 +23,14 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; package me.lucko.luckperms.common.commands.impl.generic.meta;
import me.lucko.luckperms.api.Node; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.NodeFactory; 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.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaSet extends SharedSubCommand { public class MetaSet extends SharedSubCommand {
public MetaSet() { 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.list(
Arg.create("key", true, "the key to set"), Arg.create("key", true, "the key to set"),
Arg.create("value", true, "the value to set"), Arg.create("value", true, "the value to set"),
Arg.create("server", false, "the server to add the meta pair on"), Arg.create("context...", false, "the contexts to add the meta pair in")
Arg.create("world", false, "the world to add the meta pair on")
) )
); );
} }
@ -58,35 +57,19 @@ public class MetaSet extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String key = args.get(0); String key = args.get(0);
String value = args.get(1); String value = args.get(1);
MutableContextSet context = ArgumentUtils.handleContext(2, args);
String server = ArgumentUtils.handleServer(2, args); Node n = NodeFactory.makeMetaNode(key, value).withExtraContext(context).build();
String world = ArgumentUtils.handleWorld(3, args);
Node n = NodeFactory.makeMetaNode(key, value).setServer(server).setWorld(world).build();
if (holder.hasPermission(n).asBoolean()) { if (holder.hasPermission(n).asBoolean()) {
Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName()); Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
holder.clearMetaKeys(key, server, world, false); holder.clearMetaKeys(key, context, false);
try {
holder.setPermission(n); holder.setPermission(n);
} catch (ObjectAlreadyHasException ignored) {
}
switch (ContextHelper.determine(server, world)) { Message.SET_META_SUCCESS.send(sender, key, value, holder.getFriendlyName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("meta set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("meta set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))

View File

@ -23,13 +23,14 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; package me.lucko.luckperms.common.commands.impl.generic.meta;
import me.lucko.luckperms.api.Node; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MetaSetTemp extends SharedSubCommand { public class MetaSetTemp extends SharedSubCommand {
public MetaSetTemp() { 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.list(
Arg.create("key", true, "the key to set"), Arg.create("key", true, "the key to set"),
Arg.create("value", true, "the value to set"), Arg.create("value", true, "the value to set"),
Arg.create("duration", true, "the duration until the meta value expires"), 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("context...", false, "the contexts to add the meta pair in")
Arg.create("world", false, "the world to add the meta pair on")
) )
); );
} }
@ -63,34 +62,20 @@ public class MetaSetTemp extends SharedSubCommand {
String key = args.get(0); String key = args.get(0);
String value = args.get(1); String value = args.get(1);
long duration = ArgumentUtils.handleDuration(2, args); long duration = ArgumentUtils.handleDuration(2, args);
String server = ArgumentUtils.handleServer(3, args); MutableContextSet context = ArgumentUtils.handleContext(2, args);
String world = ArgumentUtils.handleWorld(4, args);
TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); 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()) { if (holder.hasPermission(n).asBoolean()) {
Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName()); Message.ALREADY_HAS_META.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }
holder.clearMetaKeys(key, server, world, true); holder.clearMetaKeys(key, context, true);
duration = holder.setPermission(n, modifier).getValue().getExpiryUnixTime();
try { Message.SET_META_TEMP_SUCCESS.send(sender, key, value, holder.getFriendlyName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("meta settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("meta settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))

View File

@ -22,13 +22,14 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
@ -42,11 +43,10 @@ import java.util.stream.Collectors;
public class MetaUnset extends SharedSubCommand { public class MetaUnset extends SharedSubCommand {
public MetaUnset() { public MetaUnset() {
super("unset", "Unsets a meta value", Permission.USER_META_UNSET, Permission.GROUP_META_UNSET, super("unset", "Unsets a meta value", Permission.USER_META_UNSET, Permission.GROUP_META_UNSET,
Predicates.notInRange(1, 3), Predicates.is(0),
Arg.list( Arg.list(
Arg.create("key", true, "the key to unset"), Arg.create("key", true, "the key to unset"),
Arg.create("server", false, "the server to remove the meta pair on"), Arg.create("context...", false, "the contexts to remove the meta pair in")
Arg.create("world", false, "the world to remove the meta pair on")
) )
); );
} }
@ -54,22 +54,10 @@ public class MetaUnset extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String key = args.get(0); String key = args.get(0);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
holder.clearMetaKeys(key, server, world, false); holder.clearMetaKeys(key, context, false);
Message.UNSET_META_SUCCESS.send(sender, key, holder.getFriendlyName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("meta unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("meta unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))

View File

@ -22,13 +22,14 @@
package me.lucko.luckperms.common.commands.impl.generic.meta; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
@ -42,11 +43,10 @@ import java.util.stream.Collectors;
public class MetaUnsetTemp extends SharedSubCommand { public class MetaUnsetTemp extends SharedSubCommand {
public MetaUnsetTemp() { public MetaUnsetTemp() {
super("unsettemp", "Unsets a temporary meta value", Permission.USER_META_UNSETTEMP, Permission.GROUP_META_UNSETTEMP, 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.list(
Arg.create("key", true, "the key to unset"), Arg.create("key", true, "the key to unset"),
Arg.create("server", false, "the server to remove the meta pair on"), Arg.create("context...", false, "the contexts to remove the meta pair in")
Arg.create("world", false, "the world to remove the meta pair on")
) )
); );
} }
@ -54,22 +54,10 @@ public class MetaUnsetTemp extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String key = args.get(0); String key = args.get(0);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
holder.clearMetaKeys(key, server, world, true); holder.clearMetaKeys(key, context, true);
Message.UNSET_META_TEMP_SUCCESS.send(sender, key, holder.getFriendlyName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("meta unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("meta unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me> * Copyright (c) 2017 Lucko (Luck) <luck@lucko.me>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@ -20,18 +20,20 @@
* SOFTWARE. * 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SubCommand; import me.lucko.luckperms.common.commands.abstraction.SubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.Group; 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.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
@ -39,47 +41,45 @@ import me.lucko.luckperms.common.utils.Predicates;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class GroupClear extends SubCommand<Group> { public class HolderClear<T extends PermissionHolder> extends SubCommand<T> {
public GroupClear() { public HolderClear(boolean user) {
super("clear", "Clears the group's permissions and parent groups", Permission.GROUP_CLEAR, Predicates.notInRange(0, 2), super("clear", "Removes all permissions, parents and meta", user ? Permission.USER_CLEAR : Permission.GROUP_CLEAR,
Predicates.alwaysFalse(),
Arg.list( Arg.list(
Arg.create("server", false, "the server name to filter by"), Arg.create("context...", false, "the contexts to filter by")
Arg.create("world", false, "the world name to filter by")
) )
); );
} }
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, T holder, List<String> args, String label) throws CommandException {
int before = group.getNodes().size(); int before = holder.getNodes().size();
String server = ArgumentUtils.handleServer(0, args); MutableContextSet context = ArgumentUtils.handleContext(0, args);
String world = ArgumentUtils.handleWorld(1, args);
switch (ContextHelper.determine(server, world)) { if (context.isEmpty()) {
case NONE: holder.clearNodes();
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);
} else { } 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(" "))) .action("clear " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
.build().submit(plugin, sender); .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; return CommandResult.SUCCESS;
} }
} }

View File

@ -67,7 +67,7 @@ public class HolderShowTracks<T extends PermissionHolder> extends SubCommand<T>
.append(t.getName()) .append(t.getName())
.append(": ") .append(": ")
.append(Util.listToArrowSep(t.getGroups(), name)) .append(Util.listToArrowSep(t.getGroups(), name))
.append(Util.getNodeContextDescription(node)) .append(Util.getAppendableNodeContextString(node))
.append("\n") .append("\n")
); );
} }

View File

@ -22,21 +22,22 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.Group;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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 class ParentAdd extends SharedSubCommand {
public ParentAdd() { public ParentAdd() {
super("add", "Sets another group for the object to inherit permissions from", Permission.USER_PARENT_ADD, 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.list(
Arg.create("group", true, "the group to inherit from"), Arg.create("group", true, "the group to inherit from"),
Arg.create("server", false, "the server to inherit the group on"), Arg.create("context...", false, "the contexts to inherit the group in")
Arg.create("world", false, "the world to inherit the group on")
) )
); );
} }
@ -58,8 +58,7 @@ public class ParentAdd extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String groupName = ArgumentUtils.handleName(0, args); String groupName = ArgumentUtils.handleName(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
if (!plugin.getStorage().loadGroup(groupName).join()) { if (!plugin.getStorage().loadGroup(groupName).join()) {
Message.GROUP_DOES_NOT_EXIST.send(sender); Message.GROUP_DOES_NOT_EXIST.send(sender);
@ -72,21 +71,10 @@ public class ParentAdd extends SharedSubCommand {
return CommandResult.LOADING_ERROR; return CommandResult.LOADING_ERROR;
} }
try { DataMutateResult result = holder.setInheritGroup(group, context);
switch (ContextHelper.determine(server, world)) {
case NONE: if (result.asBoolean()) {
holder.setInheritGroup(group); Message.SET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("parent add " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("parent add " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -94,8 +82,7 @@ public class ParentAdd extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) {
Message.ALREADY_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName()); Message.ALREADY_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,17 +22,20 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.TemporaryModifier;
import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.PermissionHolder; 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.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getGroupTabComplete; 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 class ParentAddTemp extends SharedSubCommand {
public ParentAddTemp() { public ParentAddTemp() {
super("addtemp", "Sets another group for the object to inherit permissions from temporarily", 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.list(
Arg.create("group", true, "the group to inherit from"), Arg.create("group", true, "the group to inherit from"),
Arg.create("duration", true, "the duration of the group membership"), Arg.create("duration", true, "the duration of the group membership"),
Arg.create("server", false, "the server to add the group on"), Arg.create("context...", false, "the contexts to inherit the group in")
Arg.create("world", false, "the world to add the group on")
) )
); );
} }
@ -64,8 +66,7 @@ public class ParentAddTemp extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String groupName = ArgumentUtils.handleName(0, args); String groupName = ArgumentUtils.handleName(0, args);
long duration = ArgumentUtils.handleDuration(1, args); long duration = ArgumentUtils.handleDuration(1, args);
String server = ArgumentUtils.handleServer(2, args); MutableContextSet context = ArgumentUtils.handleContext(2, args);
String world = ArgumentUtils.handleWorld(3, args);
TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR);
if (!plugin.getStorage().loadGroup(groupName).join()) { if (!plugin.getStorage().loadGroup(groupName).join()) {
@ -79,31 +80,16 @@ public class ParentAddTemp extends SharedSubCommand {
return CommandResult.INVALID_ARGS; return CommandResult.INVALID_ARGS;
} }
try {
if (group.getName().equalsIgnoreCase(holder.getObjectName())) { if (group.getName().equalsIgnoreCase(holder.getObjectName())) {
throw new ObjectAlreadyHasException(); Message.ALREADY_TEMP_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName());
return CommandResult.STATE_ERROR;
} }
switch (ContextHelper.determine(server, world)) { Map.Entry<DataMutateResult, Node> ret = holder.setPermission(NodeFactory.newBuilder("group." + group.getName()).setExpiry(duration).withExtraContext(context).build(), modifier);
case NONE:
duration = holder.setPermission(new NodeBuilder("group." + group.getName()).setValue(true).setExpiry(duration).build(), modifier).getExpiryUnixTime(); if (ret.getKey().asBoolean()) {
Message.SET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), duration = ret.getValue().getExpiryUnixTime();
DateUtil.formatDateDiff(duration) Message.SET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context));
);
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("parent addtemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("parent addtemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -111,8 +97,7 @@ public class ParentAddTemp extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) {
Message.ALREADY_TEMP_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName()); Message.ALREADY_TEMP_INHERITS.send(sender, holder.getFriendlyName(), group.getDisplayName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,13 +22,13 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
@ -41,10 +41,9 @@ import java.util.stream.Collectors;
public class ParentClear extends SharedSubCommand { public class ParentClear extends SharedSubCommand {
public ParentClear() { 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.list(
Arg.create("server", false, "the server name to filter by"), Arg.create("context...", false, "the contexts to filter by")
Arg.create("world", false, "the world name to filter by")
) )
); );
} }
@ -53,19 +52,12 @@ public class ParentClear extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
int before = holder.getNodes().size(); int before = holder.getNodes().size();
String server = ArgumentUtils.handleServer(0, args); MutableContextSet context = ArgumentUtils.handleContext(0, args);
String world = ArgumentUtils.handleWorld(1, args);
switch (ContextHelper.determine(server, world)) { if (context.isEmpty()) {
case NONE:
holder.clearParents(true); holder.clearParents(true);
break; } else {
case SERVER: holder.clearParents(context, true);
holder.clearParents(server, true);
break;
case SERVER_AND_WORLD:
holder.clearParents(server, world, true);
break;
} }
int changed = before - holder.getNodes().size(); int changed = before - holder.getNodes().size();

View File

@ -22,6 +22,8 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; 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.constants.Permission;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import java.util.List; import java.util.List;
import java.util.SortedSet;
public class ParentInfo extends SharedSubCommand { public class ParentInfo extends SharedSubCommand {
public ParentInfo() { public ParentInfo() {
@ -43,8 +47,38 @@ public class ParentInfo extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
Message.LISTPARENTS.send(sender, holder.getFriendlyName(), Util.permGroupsToString(holder.mergePermissionsToSortedSet())); Message.LISTPARENTS.send(sender, holder.getFriendlyName(), permGroupsToString(holder.mergePermissionsToSortedSet()));
Message.LISTPARENTS_TEMP.send(sender, holder.getFriendlyName(), Util.tempGroupsToString(holder.mergePermissionsToSortedSet())); Message.LISTPARENTS_TEMP.send(sender, holder.getFriendlyName(), tempGroupsToString(holder.mergePermissionsToSortedSet()));
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} }
private static String permGroupsToString(SortedSet<LocalizedNode> 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<LocalizedNode> 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();
}
} }

View File

@ -22,23 +22,24 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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 class ParentRemove extends SharedSubCommand {
public ParentRemove() { public ParentRemove() {
super("remove", "Removes a previously set inheritance rule", Permission.USER_PARENT_REMOVE, 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.list(
Arg.create("group", true, "the group to remove"), Arg.create("group", true, "the group to remove"),
Arg.create("server", false, "the server to remove the group on"), Arg.create("context...", false, "the contexts to remove the group in")
Arg.create("world", false, "the world to remove the group on")
) )
); );
} }
@ -60,16 +60,12 @@ public class ParentRemove extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String groupName = ArgumentUtils.handleNameWithSpace(0, args); String groupName = ArgumentUtils.handleNameWithSpace(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
ContextHelper.CommandContext context = ContextHelper.determine(server, world);
if (holder instanceof User) { if (holder instanceof User) {
User user = (User) holder; User user = (User) holder;
boolean shouldPrevent = (context == ContextHelper.CommandContext.NONE || boolean shouldPrevent = (context.isEmpty() || context.has("server", "global")) &&
(context == ContextHelper.CommandContext.SERVER && server.equalsIgnoreCase("global"))) &&
plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION_METHOD).equals("stored") && plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION_METHOD).equals("stored") &&
user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(groupName); user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(groupName);
@ -79,21 +75,9 @@ public class ParentRemove extends SharedSubCommand {
} }
} }
try { DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder("group." + groupName).withExtraContext(context).build());
switch (context) { if (result.asBoolean()) {
case NONE: Message.UNSET_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName, Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("parent remove " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("parent remove " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -101,8 +85,7 @@ public class ParentRemove extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectLacksException e) {
Message.DOES_NOT_INHERIT.send(sender, holder.getFriendlyName(), groupName); Message.DOES_NOT_INHERIT.send(sender, holder.getFriendlyName(), groupName);
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,21 +22,22 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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 class ParentRemoveTemp extends SharedSubCommand {
public ParentRemoveTemp() { public ParentRemoveTemp() {
super("removetemp", "Removes a previously set temporary inheritance rule", 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.list(
Arg.create("group", true, "the group to remove"), Arg.create("group", true, "the group to remove"),
Arg.create("server", false, "the server to remove the group on"), Arg.create("context...", false, "the contexts to remove the group in")
Arg.create("world", false, "the world to remove the group on")
) )
); );
} }
@ -58,24 +58,12 @@ public class ParentRemoveTemp extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String groupName = ArgumentUtils.handleNameWithSpace(0, args); String groupName = ArgumentUtils.handleNameWithSpace(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
try { DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder("group." + groupName).setExpiry(10L).withExtraContext(context).build());
switch (ContextHelper.determine(server, world)) {
case NONE: if (result.asBoolean()) {
holder.unsetPermission(NodeFactory.make("group." + groupName, true, true)); Message.UNSET_TEMP_INHERIT_SUCCESS.send(sender, holder.getFriendlyName(), groupName, Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("parent removetemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("parent removetemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -83,8 +71,7 @@ public class ParentRemoveTemp extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectLacksException e) {
Message.DOES_NOT_TEMP_INHERIT.send(sender, holder.getFriendlyName(), groupName); Message.DOES_NOT_TEMP_INHERIT.send(sender, holder.getFriendlyName(), groupName);
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,13 +22,14 @@
package me.lucko.luckperms.common.commands.impl.generic.parent; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.Group; 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.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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 class ParentSet extends SharedSubCommand {
public ParentSet() { public ParentSet() {
super("set", "Removes all other groups the object inherits already and adds them to the one given", 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.list(
Arg.create("group", true, "the group to set to"), Arg.create("group", true, "the group to set to"),
Arg.create("server", false, "the server to set the group on"), Arg.create("context...", false, "the contexts to set the group in")
Arg.create("world", false, "the world to set the group on")
) )
); );
} }
@ -59,8 +58,7 @@ public class ParentSet extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String groupName = ArgumentUtils.handleName(0, args); String groupName = ArgumentUtils.handleName(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
if (!plugin.getStorage().loadGroup(groupName).join()) { if (!plugin.getStorage().loadGroup(groupName).join()) {
Message.GROUP_DOES_NOT_EXIST.send(sender); Message.GROUP_DOES_NOT_EXIST.send(sender);
@ -73,43 +71,13 @@ public class ParentSet extends SharedSubCommand {
return CommandResult.LOADING_ERROR; return CommandResult.LOADING_ERROR;
} }
switch (ContextHelper.determine(server, world)) { holder.clearParents(context, false);
case NONE: holder.setInheritGroup(group, context);
holder.clearParents(null, null, false);
try {
holder.setInheritGroup(group);
} catch (ObjectAlreadyHasException ignored) {}
if (holder instanceof User) { if (holder instanceof User) {
((User) holder).getPrimaryGroup().setStoredValue(group.getName()); ((User) holder).getPrimaryGroup().setStoredValue(group.getName());
} }
Message.SET_PARENT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName()); Message.SET_PARENT_SUCCESS.send(sender, holder.getFriendlyName(), group.getDisplayName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("parent set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("parent set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))

View File

@ -22,16 +22,18 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.core.model.PermissionHolder;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
@ -43,11 +45,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi
public class PermissionCheck extends SharedSubCommand { public class PermissionCheck extends SharedSubCommand {
public PermissionCheck() { public PermissionCheck() {
super("check", "Checks to see if the object has a certain permission node", Permission.USER_PERM_CHECK, 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.list(
Arg.create("node", true, "the permission node to check for"), Arg.create("node", true, "the permission node to check for"),
Arg.create("server", false, "the server to check on"), Arg.create("context...", false, "the contexts to check in")
Arg.create("world", false, "the world to check on")
) )
); );
} }
@ -55,21 +56,12 @@ public class PermissionCheck extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String node = ArgumentUtils.handleString(0, args); String node = ArgumentUtils.handleString(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
switch (ContextHelper.determine(server, world)) { Tristate result = holder.hasPermission(NodeFactory.newBuilder(node).withExtraContext(context).build());
case NONE: String s = Util.formatTristate(result);
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;
}
Message.CHECK_PERMISSION.send(sender, holder.getFriendlyName(), node, s, Util.contextSetToString(context));
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} }

View File

@ -22,17 +22,18 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.InheritanceInfo; 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.core.model.PermissionHolder;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
@ -44,11 +45,10 @@ import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getPermi
public class PermissionCheckInherits extends SharedSubCommand { public class PermissionCheckInherits extends SharedSubCommand {
public PermissionCheckInherits() { public PermissionCheckInherits() {
super("checkinherits", "Checks to see if the object inherits a certain permission node", 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.list(
Arg.create("node", true, "the permission node to check for"), Arg.create("node", true, "the permission node to check for"),
Arg.create("server", false, "the server to check on"), Arg.create("context...", false, "the contexts to check in")
Arg.create("world", false, "the world to check on")
) )
); );
} }
@ -56,29 +56,17 @@ public class PermissionCheckInherits extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String node = ArgumentUtils.handleString(0, args); String node = ArgumentUtils.handleString(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
InheritanceInfo result = null; InheritanceInfo result = holder.inheritsPermissionInfo(NodeFactory.newBuilder(node).withExtraContext(context).build());
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;
}
String location = result.getLocation().orElse(null); String location = result.getLocation().orElse(null);
if (location != null && location.equalsIgnoreCase(holder.getObjectName())) { if (location == null || location.equalsIgnoreCase(holder.getObjectName())) {
location = "self"; location = "self";
} }
Util.sendPluginMessage(sender, "&b" + node + ": " + Util.formatTristate(result.getResult()) + String s = Util.formatTristate(result.getResult());
(location != null ? " &7(inherited from &a" + location + "&7)" : "")); Message.CHECK_PERMISSION.send(sender, holder.getFriendlyName(), node, s, Util.contextSetToString(context), location);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} }

View File

@ -22,6 +22,10 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; 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.Constants;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.PermissionHolder;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import io.github.mkremins.fanciful.ChatColor;
import io.github.mkremins.fanciful.FancyMessage; import io.github.mkremins.fanciful.FancyMessage;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.SortedSet;
public class PermissionInfo extends SharedSubCommand { public class PermissionInfo extends SharedSubCommand {
public PermissionInfo() { public PermissionInfo() {
super("info", "Lists the permission nodes the object has", Permission.USER_PERM_INFO, 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.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 @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> 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)) { if (sender.getUuid().equals(Constants.CONSOLE_UUID)) {
Message.LISTNODES.send(sender, holder.getFriendlyName()); Message.LISTNODES.send(sender, holder.getFriendlyName());
sender.sendMessage(Util.color(Util.permNodesToStringConsole(holder.mergePermissionsToSortedSet()))); sender.sendMessage(Util.color(permNodesToString(filter, holder.mergePermissionsToSortedSet())));
} else { } else {
int page = ArgumentUtils.handleIntOrElse(0, args, 1); int page = ArgumentUtils.handleIntOrElse(0, args, 1);
Map.Entry<FancyMessage, String> ent = Util.permNodesToMessage(holder.mergePermissionsToSortedSet(), holder, label, page); Map.Entry<FancyMessage, String> ent = permNodesToMessage(filter, holder.mergePermissionsToSortedSet(), holder, label, page);
if (ent.getValue() != null) { if (ent.getValue() != null) {
Message.LISTNODES_WITH_PAGE.send(sender, holder.getFriendlyName(), ent.getValue()); Message.LISTNODES_WITH_PAGE.send(sender, holder.getFriendlyName(), ent.getValue());
sender.sendMessage(ent.getKey()); 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; return CommandResult.SUCCESS;
} }
private static Map.Entry<FancyMessage, String> permNodesToMessage(String filter, SortedSet<LocalizedNode> nodes, PermissionHolder holder, String label, int pageNumber) {
List<Node> 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<List<Node>> pages = Util.divideList(l, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<Node> 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<LocalizedNode> 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<LocalizedNode> 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();
}
} }

View File

@ -22,21 +22,22 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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 class PermissionSet extends SharedSubCommand {
public PermissionSet() { public PermissionSet() {
super("set", "Sets a permission for the object", Permission.USER_PERM_SET, Permission.GROUP_PERM_SET, 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.list(
Arg.create("node", true, "the permission node to set"), Arg.create("node", true, "the permission node to set"),
Arg.create("true|false", false, "the value of the node"), Arg.create("true|false", false, "the value of the node"),
Arg.create("server", false, "the server to add the permission node on"), Arg.create("context...", false, "the contexts to add the permission in")
Arg.create("world", false, "the world to add the permission node on")
) )
); );
} }
@ -61,25 +61,12 @@ public class PermissionSet extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
boolean b = ArgumentUtils.handleBoolean(1, args); boolean b = ArgumentUtils.handleBoolean(1, args);
String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args); String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args);
MutableContextSet context = ArgumentUtils.handleContext(2, args);
String server = ArgumentUtils.handleServer(2, args); DataMutateResult result = holder.setPermission(NodeFactory.newBuilder(node).setValue(b).withExtraContext(context).build());
String world = ArgumentUtils.handleWorld(3, args);
try { if (result.asBoolean()) {
switch (ContextHelper.determine(server, world)) { Message.SETPERMISSION_SUCCESS.send(sender, node, b, holder.getFriendlyName(), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("permission set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("permission set " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -87,8 +74,7 @@ public class PermissionSet extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) {
Message.ALREADY_HASPERMISSION.send(sender, holder.getFriendlyName()); Message.ALREADY_HASPERMISSION.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,26 +22,29 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.TemporaryModifier;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil; import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static me.lucko.luckperms.common.commands.abstraction.SubCommand.getBoolTabComplete; 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 class PermissionSetTemp extends SharedSubCommand {
public PermissionSetTemp() { public PermissionSetTemp() {
super("settemp", "Sets a permission for the object temporarily", Permission.USER_PERM_SETTEMP, 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.list(
Arg.create("node", true, "the permission node to set"), Arg.create("node", true, "the permission node to set"),
Arg.create("true|false", false, "the value of the node"), Arg.create("true|false", false, "the value of the node"),
Arg.create("duration", true, "the duration until the permission node expires"), 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("context...", false, "the contexts to add the permission in")
Arg.create("world", false, "the world to add the permission node on")
) )
); );
} }
@ -65,35 +67,15 @@ public class PermissionSetTemp extends SharedSubCommand {
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
boolean b = ArgumentUtils.handleBoolean(1, args); boolean b = ArgumentUtils.handleBoolean(1, args);
String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args); String node = b ? ArgumentUtils.handleNode(0, args) : ArgumentUtils.handleString(0, args);
long duration = ArgumentUtils.handleDuration(2, args); long duration = ArgumentUtils.handleDuration(2, args);
MutableContextSet context = ArgumentUtils.handleContext(3, args);
String server = ArgumentUtils.handleServer(3, args);
String world = ArgumentUtils.handleWorld(4, args);
TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR); TemporaryModifier modifier = plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR);
Map.Entry<DataMutateResult, Node> result = holder.setPermission(NodeFactory.newBuilder(node).setValue(b).withExtraContext(context).setExpiry(duration).build(), modifier);
try { if (result.getKey().asBoolean()) {
switch (ContextHelper.determine(server, world)) { duration = result.getValue().getExpiryUnixTime();
case NONE: Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, b, holder.getFriendlyName(), DateUtil.formatDateDiff(duration), Util.contextSetToString(context));
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;
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("permission settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("permission settemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -101,8 +83,7 @@ public class PermissionSetTemp extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectAlreadyHasException e) {
Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, holder.getFriendlyName()); Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,21 +22,22 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -44,11 +45,10 @@ import java.util.stream.Collectors;
public class PermissionUnset extends SharedSubCommand { public class PermissionUnset extends SharedSubCommand {
public PermissionUnset() { public PermissionUnset() {
super("unset", "Unsets a permission for the object", Permission.USER_PERM_UNSET, Permission.GROUP_PERM_UNSET, 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.list(
Arg.create("node", true, "the permission node to unset"), Arg.create("node", true, "the permission node to unset"),
Arg.create("server", false, "the server to remove the permission node on"), Arg.create("context...", false, "the contexts to remove the permission in")
Arg.create("world", false, "the world to remove the permission node on")
) )
); );
} }
@ -56,52 +56,27 @@ public class PermissionUnset extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String node = ArgumentUtils.handleString(0, args); String node = ArgumentUtils.handleString(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
try { DataMutateResult result;
// unset exact - with false value only
if (node.startsWith("group.")) { if (node.startsWith("group.")) {
switch (ContextHelper.determine(server, world)) { // unset exact - with false value only
case NONE: result = holder.unsetPermissionExact(NodeFactory.newBuilder(node).setValue(false).withExtraContext(context).build());
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 { } else {
// standard unset // standard unset
switch (ContextHelper.determine(server, world)) { result = holder.unsetPermission(NodeFactory.newBuilder(node).withExtraContext(context).build());
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;
}
} }
if (result.asBoolean()) {
Message.UNSETPERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName(), Util.contextSetToString(context));
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("permission unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("permission unset " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
.build().submit(plugin, sender); .build().submit(plugin, sender);
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectLacksException e) {
Message.DOES_NOT_HAVEPERMISSION.send(sender, holder.getFriendlyName()); Message.DOES_NOT_HAVEPERMISSION.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -22,21 +22,22 @@
package me.lucko.luckperms.common.commands.impl.generic.permission; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand; import me.lucko.luckperms.common.commands.abstraction.SharedSubCommand;
import me.lucko.luckperms.common.commands.sender.Sender; import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.ArgumentUtils; 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.Message;
import me.lucko.luckperms.common.constants.Permission; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.data.LogEntry; import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -44,11 +45,10 @@ import java.util.stream.Collectors;
public class PermissionUnsetTemp extends SharedSubCommand { public class PermissionUnsetTemp extends SharedSubCommand {
public PermissionUnsetTemp() { public PermissionUnsetTemp() {
super("unsettemp", "Unsets a temporary permission for the object", Permission.USER_PERM_UNSETTEMP, 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.list(
Arg.create("node", true, "the permission node to unset"), Arg.create("node", true, "the permission node to unset"),
Arg.create("server", false, "the server to remove the permission node on"), Arg.create("context...", false, "the contexts to remove the permission in")
Arg.create("world", false, "the world to remove the permission node on")
) )
); );
} }
@ -56,42 +56,12 @@ public class PermissionUnsetTemp extends SharedSubCommand {
@Override @Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException { public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder holder, List<String> args, String label) throws CommandException {
String node = ArgumentUtils.handleString(0, args); String node = ArgumentUtils.handleString(0, args);
String server = ArgumentUtils.handleServer(1, args); MutableContextSet context = ArgumentUtils.handleContext(1, args);
String world = ArgumentUtils.handleWorld(2, args);
try { DataMutateResult result = holder.unsetPermission(NodeFactory.newBuilder(node).setExpiry(10L).withExtraContext(context).build());
// unset exact - with false value only
if (node.startsWith("group.")) { if (result.asBoolean()) {
switch (ContextHelper.determine(server, world)) { Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, holder.getFriendlyName(), Util.contextSetToString(context));
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;
}
}
LogEntry.build().actor(sender).acted(holder) LogEntry.build().actor(sender).acted(holder)
.action("permission unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" "))) .action("permission unsettemp " + args.stream().map(ArgumentUtils.WRAPPER).collect(Collectors.joining(" ")))
@ -99,8 +69,7 @@ public class PermissionUnsetTemp extends SharedSubCommand {
save(holder, sender, plugin); save(holder, sender, plugin);
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} else {
} catch (ObjectLacksException e) {
Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, holder.getFriendlyName()); Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, holder.getFriendlyName());
return CommandResult.STATE_ERROR; return CommandResult.STATE_ERROR;
} }

View File

@ -34,8 +34,6 @@ import me.lucko.luckperms.common.core.NodeFactory;
import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -95,19 +93,8 @@ public class GroupBulkChange extends SubCommand<Group> {
} }
} }
toRemove.forEach(n -> { toRemove.forEach(group::unsetPermission);
try { toAdd.forEach(group::setPermission);
group.unsetPermission(n);
} catch (ObjectLacksException ignored) {
}
});
toAdd.forEach(n -> {
try {
group.setPermission(n);
} catch (ObjectAlreadyHasException ignored) {
}
});
save(group, sender, plugin); save(group, sender, plugin);
Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size()); Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size());

View File

@ -70,14 +70,14 @@ public class GroupInfo extends SubCommand<Group> {
if (!parents.isEmpty()) { if (!parents.isEmpty()) {
Message.INFO_PARENT_HEADER.send(sender); Message.INFO_PARENT_HEADER.send(sender);
for (Node node : parents) { 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()) { if (!tempParents.isEmpty()) {
Message.INFO_TEMP_PARENT_HEADER.send(sender); Message.INFO_TEMP_PARENT_HEADER.send(sender);
for (Node node : tempParents) { 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())); Message.EMPTY.send(sender, "&f- &2- expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime()));
} }
} }

View File

@ -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.Command;
import me.lucko.luckperms.common.commands.abstraction.MainCommand; 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.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.other.HolderShowTracks;
import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent; import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent;
import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission; import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission;
@ -48,7 +49,7 @@ public class GroupMainCommand extends MainCommand<Group> {
.add(new GroupSetWeight()) .add(new GroupSetWeight())
.add(new HolderShowTracks<>(false)) .add(new HolderShowTracks<>(false))
.add(new GroupBulkChange()) .add(new GroupBulkChange())
.add(new GroupClear()) .add(new HolderClear<>(false))
.add(new GroupRename()) .add(new GroupRename())
.add(new GroupClone()) .add(new GroupClone())
.build() .build()

View File

@ -49,7 +49,7 @@ public class GroupSetWeight extends SubCommand<Group> {
int weight = ArgumentUtils.handlePriority(0, args); int weight = ArgumentUtils.handlePriority(0, args);
group.removeIf(n -> n.getPermission().startsWith("weight.")); 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); save(group, sender, plugin);
Message.GROUP_SET_WEIGHT.send(sender, weight, group.getDisplayName()); Message.GROUP_SET_WEIGHT.send(sender, weight, group.getDisplayName());

View File

@ -45,7 +45,7 @@ public class MigrationUtils {
public static void setGroupWeight(Group group, int weight) { public static void setGroupWeight(Group group, int weight) {
group.removeIf(n -> n.getPermission().startsWith("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) { public static String standardizeName(String string) {

View File

@ -22,7 +22,10 @@
package me.lucko.luckperms.common.commands.impl.misc; 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.HeldPermission;
import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.common.commands.Arg; import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; 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.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission; 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.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.DateUtil;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import io.github.mkremins.fanciful.ChatColor;
import io.github.mkremins.fanciful.FancyMessage; import io.github.mkremins.fanciful.FancyMessage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
public class SearchCommand extends SingleCommand { public class SearchCommand extends SingleCommand {
public SearchCommand() { public SearchCommand() {
@ -78,8 +87,8 @@ public class SearchCommand extends SingleCommand {
return s; return s;
}); });
Map.Entry<FancyMessage, String> msgUsers = Util.searchUserResultToMessage(matchedUsers, lookupFunc, label, page); Map.Entry<FancyMessage, String> msgUsers = searchUserResultToMessage(matchedUsers, lookupFunc, label, page);
Map.Entry<FancyMessage, String> msgGroups = Util.searchGroupResultToMessage(matchedGroups, label, page); Map.Entry<FancyMessage, String> msgGroups = searchGroupResultToMessage(matchedGroups, label, page);
if (msgUsers.getValue() != null) { if (msgUsers.getValue() != null) {
Message.SEARCH_SHOWING_USERS_WITH_PAGE.send(sender, msgUsers.getValue()); Message.SEARCH_SHOWING_USERS_WITH_PAGE.send(sender, msgUsers.getValue());
@ -99,4 +108,107 @@ public class SearchCommand extends SingleCommand {
return CommandResult.SUCCESS; return CommandResult.SUCCESS;
} }
private static Map.Entry<FancyMessage, String> searchUserResultToMessage(List<HeldPermission<UUID>> results, Function<UUID, String> uuidLookup, String label, int pageNumber) {
if (results.isEmpty()) {
return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
}
List<HeldPermission<UUID>> sorted = new ArrayList<>(results);
sorted.sort(Comparator.comparing(HeldPermission::getHolder));
int index = pageNumber - 1;
List<List<HeldPermission<UUID>>> pages = Util.divideList(sorted, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<HeldPermission<UUID>> page = pages.get(index);
List<Map.Entry<String, HeldPermission<UUID>>> 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<String, HeldPermission<UUID>> 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<FancyMessage, String> searchGroupResultToMessage(List<HeldPermission<String>> results, String label, int pageNumber) {
if (results.isEmpty()) {
return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
}
List<HeldPermission<String>> sorted = new ArrayList<>(results);
sorted.sort(Comparator.comparing(HeldPermission::getHolder));
int index = pageNumber - 1;
List<List<HeldPermission<String>>> pages = Util.divideList(sorted, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<HeldPermission<String>> 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<String> 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);
}
} }

View File

@ -34,8 +34,6 @@ import me.lucko.luckperms.common.core.NodeFactory;
import me.lucko.luckperms.common.core.model.User; import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -105,19 +103,8 @@ public class UserBulkChange extends SubCommand<User> {
} }
} }
toRemove.forEach(n -> { toRemove.forEach(user::unsetPermission);
try { toAdd.forEach(user::setPermission);
user.unsetPermission(n);
} catch (ObjectLacksException ignored) {
}
});
toAdd.forEach(n -> {
try {
user.setPermission(n);
} catch (ObjectAlreadyHasException ignored) {
}
});
save(user, sender, plugin); save(user, sender, plugin);
Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size()); Message.BULK_CHANGE_SUCCESS.send(sender, toAdd.size());

View File

@ -1,85 +0,0 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<User> {
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<String> 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;
}
}

View File

@ -43,7 +43,6 @@ import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.ArgumentChecker; import me.lucko.luckperms.common.utils.ArgumentChecker;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.HashSet; import java.util.HashSet;
@ -137,9 +136,7 @@ public class UserDemote extends SubCommand<User> {
if (previous == null) { if (previous == null) {
try {
user.unsetPermission(oldNode); user.unsetPermission(oldNode);
} catch (ObjectLacksException ignored) {}
Message.USER_DEMOTE_ENDOFTRACK.send(sender, track.getName(), user.getName(), old); Message.USER_DEMOTE_ENDOFTRACK.send(sender, track.getName(), user.getName(), old);
@ -163,12 +160,8 @@ public class UserDemote extends SubCommand<User> {
return CommandResult.LOADING_ERROR; return CommandResult.LOADING_ERROR;
} }
try {
user.unsetPermission(oldNode); user.unsetPermission(oldNode);
} catch (ObjectLacksException ignored) {}
try {
user.setPermission(NodeFactory.newBuilder("group." + previousGroup.getName()).setServer(server).setWorld(world).build()); user.setPermission(NodeFactory.newBuilder("group." + previousGroup.getName()).setServer(server).setWorld(world).build());
} catch (ObjectAlreadyHasException ignored) {}
if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) { if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) {
user.getPrimaryGroup().setStoredValue(previousGroup.getName()); user.getPrimaryGroup().setStoredValue(previousGroup.getName());

View File

@ -75,14 +75,14 @@ public class UserInfo extends SubCommand<User> {
if (!parents.isEmpty()) { if (!parents.isEmpty()) {
Message.INFO_PARENT_HEADER.send(sender); Message.INFO_PARENT_HEADER.send(sender);
for (Node node : parents) { 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()) { if (!tempParents.isEmpty()) {
Message.INFO_TEMP_PARENT_HEADER.send(sender); Message.INFO_TEMP_PARENT_HEADER.send(sender);
for (Node node : tempParents) { 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())); Message.EMPTY.send(sender, "&f- &2- expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime()));
} }
} }

View File

@ -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.Command;
import me.lucko.luckperms.common.commands.abstraction.MainCommand; 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.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.other.HolderShowTracks;
import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent; import me.lucko.luckperms.common.commands.impl.generic.parent.CommandParent;
import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission; import me.lucko.luckperms.common.commands.impl.generic.permission.CommandPermission;
@ -53,7 +54,7 @@ public class UserMainCommand extends MainCommand<User> {
.add(new UserDemote()) .add(new UserDemote())
.add(new HolderShowTracks<>(true)) .add(new HolderShowTracks<>(true))
.add(new UserBulkChange()) .add(new UserBulkChange())
.add(new UserClear()) .add(new HolderClear<>(true))
.build() .build()
); );
} }

View File

@ -43,7 +43,6 @@ import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.ArgumentChecker; import me.lucko.luckperms.common.utils.ArgumentChecker;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.HashSet; import java.util.HashSet;
@ -124,9 +123,7 @@ public class UserPromote extends SubCommand<User> {
return CommandResult.LOADING_ERROR; return CommandResult.LOADING_ERROR;
} }
try {
user.setPermission(NodeFactory.newBuilder("group." + first).setServer(server).setWorld(world).build()); user.setPermission(NodeFactory.newBuilder("group." + first).setServer(server).setWorld(world).build());
} catch (ObjectAlreadyHasException ignored) {}
switch (ContextHelper.determine(server, world)) { switch (ContextHelper.determine(server, world)) {
case NONE: case NONE:
@ -180,12 +177,8 @@ public class UserPromote extends SubCommand<User> {
return CommandResult.LOADING_ERROR; return CommandResult.LOADING_ERROR;
} }
try {
user.unsetPermission(oldNode); user.unsetPermission(oldNode);
} catch (ObjectLacksException ignored) {}
try {
user.setPermission(NodeFactory.newBuilder("group." + nextGroup.getName()).setServer(server).setWorld(world).build()); user.setPermission(NodeFactory.newBuilder("group." + nextGroup.getName()).setServer(server).setWorld(world).build());
} catch (ObjectAlreadyHasException ignored) {}
if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) { if (server == null && world == null && user.getPrimaryGroup().getStoredValue().equalsIgnoreCase(old)) {
user.getPrimaryGroup().setStoredValue(nextGroup.getName()); user.getPrimaryGroup().setStoredValue(nextGroup.getName());
@ -207,6 +200,7 @@ public class UserPromote extends SubCommand<User> {
LogEntry.build().actor(sender).acted(user) LogEntry.build().actor(sender).acted(user)
.action("promote " + args.stream().collect(Collectors.joining(" "))) .action("promote " + args.stream().collect(Collectors.joining(" ")))
.build().submit(plugin, sender); .build().submit(plugin, sender);
save(user, sender, plugin); save(user, sender, plugin);
plugin.getApiProvider().getEventFactory().handleUserPromote(user, track, old, nextGroup.getName()); plugin.getApiProvider().getEventFactory().handleUserPromote(user, track, old, nextGroup.getName());
return CommandResult.SUCCESS; return CommandResult.SUCCESS;

View File

@ -22,6 +22,7 @@
package me.lucko.luckperms.common.commands.impl.user; 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.Arg;
import me.lucko.luckperms.common.commands.CommandException; import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult; 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.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates; import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.util.List; import java.util.List;
@ -66,10 +66,7 @@ public class UserSwitchPrimaryGroup extends SubCommand<User> {
if (!user.inheritsGroup(group)) { if (!user.inheritsGroup(group)) {
Message.USER_PRIMARYGROUP_ERROR_NOTMEMBER.send(sender, user.getName(), group.getName()); Message.USER_PRIMARYGROUP_ERROR_NOTMEMBER.send(sender, user.getName(), group.getName());
try { user.setInheritGroup(group, ContextSet.empty());
user.setInheritGroup(group);
} catch (ObjectAlreadyHasException ignored) {
}
} }
user.getPrimaryGroup().setStoredValue(group.getName()); user.getPrimaryGroup().setStoredValue(group.getName());

View File

@ -35,8 +35,6 @@ import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.utils.Predicates; 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.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -135,19 +133,8 @@ public class BulkEditGroup extends SubCommand<Storage> {
} }
} }
toRemove.forEach(n -> { toRemove.forEach(user::unsetPermission);
try { toAdd.forEach(user::setPermission);
user.unsetPermission(n);
} catch (ObjectLacksException ignored) {
}
});
toAdd.forEach(n -> {
try {
user.setPermission(n);
} catch (ObjectAlreadyHasException ignored) {
}
});
plugin.getStorage().saveUser(user); plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user); plugin.getUserManager().cleanup(user);

View File

@ -35,8 +35,6 @@ import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.Storage; import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.utils.Predicates; 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.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -125,19 +123,8 @@ public class BulkEditPermission extends SubCommand<Storage> {
} }
} }
toRemove.forEach(n -> { toRemove.forEach(user::unsetPermission);
try { toAdd.forEach(user::setPermission);
user.unsetPermission(n);
} catch (ObjectLacksException ignored) {
}
});
toAdd.forEach(n -> {
try {
user.setPermission(n);
} catch (ObjectAlreadyHasException ignored) {
}
});
plugin.getStorage().saveUser(user); plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user); plugin.getUserManager().cleanup(user);

View File

@ -138,10 +138,9 @@ public class ArgumentUtils {
public static MutableContextSet handleContext(int fromIndex, List<String> args) { public static MutableContextSet handleContext(int fromIndex, List<String> args) {
if (args.size() > fromIndex) { if (args.size() > fromIndex) {
MutableContextSet set = MutableContextSet.create(); MutableContextSet set = MutableContextSet.create();
List<String> contexts = args.subList(fromIndex, args.size() - 1); List<String> contexts = args.subList(fromIndex, args.size());
for (int i = 0; i < contexts.size(); i++) { for (int i = 0; i < contexts.size(); i++) {
String pair = contexts.get(i); String pair = contexts.get(i);

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<Map.Entry<Integer, ?>> {
public static final MetaComparator INSTANCE = new MetaComparator();
@Override
public int compare(Map.Entry<Integer, ?> o1, Map.Entry<Integer, ?> o2) {
int result = Integer.compare(o1.getKey(), o2.getKey());
return result != 0 ? result : 1;
}
}

View File

@ -26,38 +26,32 @@ import lombok.experimental.UtilityClass;
import com.google.common.collect.Maps; 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.Node;
import me.lucko.luckperms.api.Tristate; 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.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Patterns; 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 io.github.mkremins.fanciful.FancyMessage;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.SortedSet;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@UtilityClass @UtilityClass
public class Util { 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) { public static void sendPluginMessage(Sender sender, String message) {
String prefix = sender.getPlatform().getLocaleManager().getTranslation(Message.PREFIX); String prefix = sender.getPlatform().getLocaleManager().getTranslation(Message.PREFIX);
if (prefix == null) { if (prefix == null) {
@ -66,6 +60,12 @@ public class Util {
sender.sendMessage(color(prefix + message)); 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<String> stripQuotes(List<String> input) { public static List<String> stripQuotes(List<String> input) {
input = new ArrayList<>(input); input = new ArrayList<>(input);
ListIterator<String> iterator = input.listIterator(); ListIterator<String> iterator = input.listIterator();
@ -82,15 +82,17 @@ public class Util {
return input; return input;
} }
/**
* Colorizes a message.
*
* @param s the message to colorize
* @return a colored message
*/
public static String color(String s) { public static String color(String s) {
return translateAlternateColorCodes('&', s); char[] b = s.toCharArray();
}
public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) {
char[] b = textToTranslate.toCharArray();
for (int i = 0; i < b.length - 1; ++i) { 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] = 167;
b[i + 1] = Character.toLowerCase(b[i + 1]); b[i + 1] = Character.toLowerCase(b[i + 1]);
} }
@ -99,249 +101,16 @@ public class Util {
return new String(b); 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) { public static String stripColor(String s) {
return s == null ? null : Patterns.STRIP_COLOR_PATTERN.matcher(s).replaceAll(""); 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<String, String> 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<String, String> 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<LocalizedNode> 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<FancyMessage, String> permNodesToMessage(SortedSet<LocalizedNode> nodes, PermissionHolder holder, String label, int pageNumber) {
List<Node> 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<List<Node>> pages = divideList(l, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<Node> 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<FancyMessage, String> searchUserResultToMessage(List<HeldPermission<UUID>> results, Function<UUID, String> uuidLookup, String label, int pageNumber) {
if (results.isEmpty()) {
return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
}
List<HeldPermission<UUID>> sorted = new ArrayList<>(results);
sorted.sort(Comparator.comparing(HeldPermission::getHolder));
int index = pageNumber - 1;
List<List<HeldPermission<UUID>>> pages = divideList(sorted, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<HeldPermission<UUID>> page = pages.get(index);
List<Map.Entry<String, HeldPermission<UUID>>> 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<String, HeldPermission<UUID>> 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<FancyMessage, String> searchGroupResultToMessage(List<HeldPermission<String>> results, String label, int pageNumber) {
if (results.isEmpty()) {
return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
}
List<HeldPermission<String>> sorted = new ArrayList<>(results);
sorted.sort(Comparator.comparing(HeldPermission::getHolder));
int index = pageNumber - 1;
List<List<HeldPermission<String>>> pages = divideList(sorted, 15);
if (index < 0 || index >= pages.size()) {
pageNumber = 1;
index = 0;
}
List<HeldPermission<String>> 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<String> 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 <T> List<List<T>> divideList(Iterable<T> source, int size) { public static <T> List<List<T>> divideList(Iterable<T> source, int size) {
List<List<T>> lists = new ArrayList<>(); List<List<T>> lists = new ArrayList<>();
Iterator<T> it = source.iterator(); Iterator<T> it = source.iterator();
@ -355,60 +124,12 @@ public class Util {
return lists; return lists;
} }
public static String tempNodesToString(SortedSet<LocalizedNode> 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<LocalizedNode> 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<LocalizedNode> 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) { public static UUID parseUuid(String s) {
try { try {
return UUID.fromString(s); return UUID.fromString(s);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
try { try {
return UUID.fromString(s.replaceAll( return UUID.fromString(s.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5"));
} catch (IllegalArgumentException e1) { } catch (IllegalArgumentException e1) {
return null; return null;
} }
@ -416,57 +137,142 @@ public class Util {
} }
public static String toCommaSep(Collection<String> strings) { public static String toCommaSep(Collection<String> strings) {
if (strings.isEmpty()) return "&bNone"; if (strings.isEmpty()) {
return "&bNone";
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
strings.forEach(s -> sb.append("&3").append(s).append("&7, ")); strings.forEach(s -> sb.append("&3").append(s).append("&7, "));
return sb.delete(sb.length() - 2, sb.length()).toString(); return sb.delete(sb.length() - 2, sb.length()).toString();
} }
public static String listToArrowSep(List<String> strings, String highlight) { public static String listToArrowSep(Collection<String> strings, String highlight) {
if (strings.isEmpty()) return "&bNone"; if (strings.isEmpty()) {
return "&bNone";
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String s : strings) { strings.forEach(s -> sb.append(s.equalsIgnoreCase(highlight) ? "&b" : "&3").append(s).append("&7 ---> "));
if (s.equalsIgnoreCase(highlight)) {
sb.append("&b").append(s).append("&7 ---> ");
} else {
sb.append("&3").append(s).append("&7 ---> ");
}
}
return sb.delete(sb.length() - 6, sb.length()).toString(); return sb.delete(sb.length() - 6, sb.length()).toString();
} }
public static String listToArrowSep(List<String> strings, String highlightFirst, String highlightSecond, boolean reversed) { public static String listToArrowSep(Collection<String> strings, String highlightFirst, String highlightSecond, boolean reversed) {
if (strings.isEmpty()) return "&6None"; if (strings.isEmpty()) {
return "&6None";
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String s : strings) { for (String s : strings) {
if (s.equalsIgnoreCase(highlightFirst)) { 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)) { } else if (s.equalsIgnoreCase(highlightSecond)) {
sb.append("&b").append(s).append("&7").append(reversed ? " <--- " : " ---> "); sb.append("&b").append(s).append("&7");
} else { } 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(); return sb.delete(sb.length() - 6, sb.length()).toString();
} }
public static String listToArrowSep(List<String> strings) { public static String listToArrowSep(List<String> strings) {
if (strings.isEmpty()) return "&6None"; if (strings.isEmpty()) {
return "&6None";
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
strings.forEach(s -> sb.append("&3").append(s).append("&b ---> ")); strings.forEach(s -> sb.append("&3").append(s).append("&b ---> "));
return sb.delete(sb.length() - 6, sb.length()).toString(); return sb.delete(sb.length() - 6, sb.length()).toString();
} }
public static class MetaComparator implements Comparator<Map.Entry<Integer, ?>> { /**
* 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<Integer, ?> o1, Map.Entry<Integer, ?> o2) { * Formats a tristate to a colored string
int result = Integer.compare(o1.getKey(), o2.getKey()); *
return result != 0 ? result : 1; * @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<String, String> 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<String, String> 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<String, String> 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<String, String> 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();
}
} }

View File

@ -201,34 +201,24 @@ public enum Message {
LIST_TRACKS("&b{0}'s Tracks:" + "\n" + "{1}", true), LIST_TRACKS("&b{0}'s Tracks:" + "\n" + "{1}", true),
LIST_TRACKS_EMPTY("{0} is not on any tracks.", 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), CONTEXT_PAIR_INLINE("&3{0}=&b{1}", false),
SETPERMISSION_SERVER_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a on server &b{3}&a.", true), CONTEXT_PAIR__GLOBAL_INLINE("&eglobal", false),
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), CONTEXT_PAIR_END("&a.", false),
SETPERMISSION_TEMP_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a for a duration of &b{3}&a.", true), CONTEXT_PAIR_SEP("&a, ", false),
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),
SET_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a.", true), CONTEXT_PAIR("&8(&7{0}=&f{1}&8)", false),
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), CHECK_PERMISSION("&b{0}&a has permission &b{1}&a set to {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.", 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),
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), SETPERMISSION_SUCCESS("&aSet &b{0}&a to &b{1}&a for &b{2}&a in context {3}&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), 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),
SET_TEMP_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a for a duration of &b{2}&a.", true), UNSETPERMISSION_SUCCESS("&aUnset &b{0}&a for &b{1}&a in context {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), UNSET_TEMP_PERMISSION_SUCCESS("&aUnset temporary permission &b{0}&a for &b{1}&a in context {2}&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), SET_INHERIT_SUCCESS("&b{0}&a now inherits permissions from &b{1}&a in context {2}&a.", true),
UNSET_INHERIT_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&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),
UNSET_INHERIT_SERVER_SUCCESS("&b{0}&a no longer inherits permissions from &b{1}&a on server &b{2}&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_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_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.", true), UNSET_TEMP_INHERIT_SUCCESS("&b{0}&a no longer temporarily inherits permissions from &b{1}&a in context {2}&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),
CLEAR_SUCCESS("&b{0}&a's permissions were cleared. (&b{1}&a nodes were removed.)", 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), 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), 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("&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), 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), ILLEGAL_DATE_ERROR("Could not parse date '{0}'.", true),
PAST_DATE_ERROR("You cannot set a date in the past!", 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_NONE("&b{0} has no meta.", true),
META_INVALID_PRIORITY("Invalid priority '{0}'. Expected a number.", 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), ALREADY_HAS_CHAT_META("{0} already has that {1} set.", 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), DOES_NOT_HAVE_CHAT_META("{0} doesn't have that {1} set.", 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),
ADDSUFFIX_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a set at a priority of &b{2}&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),
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), 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),
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), REMOVE_CHATMETA_SUCCESS("&b{0}&a had {1} &f\"{2}&f\"&a at priority &b{3}&a removed in context {4}&a.", true),
REMOVESUFFIX_SUCCESS("&b{0}&a had suffix &f\"{1}&f\"&a at priority &b{2}&a removed.", true), BULK_REMOVE_CHATMETA_SUCCESS("&b{0}&a had all {1}es at priority &b{3}&a removed in context {4}&a.", 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), 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),
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), BULK_REMOVE_TEMP_CHATMETA_SUCCESS("&b{0}&a had all temporary {1}es at priority &b{3}&a removed in context {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),
ALREADY_HAS_META("{0} already has that meta key value pair set.", 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_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_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_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),
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), UNSET_META_SUCCESS("&aUnset meta value with key &f\"{0}&f\"&a for &b{1}&a in context {2}&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), UNSET_META_TEMP_SUCCESS("&aUnset temporary meta value with key &f\"{0}&f\"&a for &b{1}&a in context {2}&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),
BULK_CHANGE_TYPE_ERROR("Invalid type. Was expecting 'server' or 'world'.", 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), BULK_CHANGE_SUCCESS("&aApplied bulk change successfully. {0} records were changed.", true),
@ -450,42 +410,32 @@ public enum Message {
@Override @Override
public String toString() { public String toString() {
return Util.color(showPrefix ? PREFIX + message : message); return asString(null);
} }
public String asString(LocaleManager localeManager) { public String asString(LocaleManager localeManager, Object... objects) {
String prefix = localeManager.getTranslation(PREFIX); String prefix = null;
if (localeManager != null) {
prefix = localeManager.getTranslation(PREFIX);
}
if (prefix == null) { if (prefix == null) {
prefix = PREFIX.getMessage(); prefix = PREFIX.getMessage();
} }
String s = localeManager.getTranslation(this); String s = null;
if (localeManager != null) {
s = localeManager.getTranslation(this);
}
if (s == null) { if (s == null) {
s = message; s = message;
} }
s = s.replace("{PREFIX}", prefix).replace("\\n", "\n"); s = format(s.replace("{PREFIX}", prefix).replace("\\n", "\n"), objects);
return Util.color(showPrefix ? (prefix + s) : (s)); return Util.color(showPrefix ? prefix + s : s);
} }
public void send(Sender sender, Object... objects) { public void send(Sender sender, Object... objects) {
String prefix = sender.getPlatform().getLocaleManager().getTranslation(PREFIX); sender.sendMessage(asString(sender.getPlatform().getLocaleManager(), objects));
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)));
}
} }
/** /**

View File

@ -24,8 +24,6 @@ package me.lucko.luckperms.common.contexts;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import com.google.common.collect.Maps;
import me.lucko.luckperms.api.context.ContextCalculator; import me.lucko.luckperms.api.context.ContextCalculator;
import me.lucko.luckperms.api.context.MutableContextSet; import me.lucko.luckperms.api.context.MutableContextSet;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
@ -39,7 +37,10 @@ public class ServerCalculator<T> implements ContextCalculator<T> {
@Override @Override
public MutableContextSet giveApplicableContext(T subject, MutableContextSet accumulator) { 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; return accumulator;
} }

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* 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<? extends Exception> 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 <T extends Throwable> void sneakyThrow0(Throwable t) throws T {
throw (T) t;
}
}

View File

@ -22,6 +22,7 @@
package me.lucko.luckperms.common.core; package me.lucko.luckperms.common.core;
import lombok.AccessLevel;
import lombok.NonNull; import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -40,8 +41,8 @@ import java.util.Set;
/** /**
* Builds Nodes * Builds Nodes
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public class NodeBuilder implements Node.Builder { class NodeBuilder implements Node.Builder {
private final String permission; private final String permission;
private final MutableContextSet extraContexts = MutableContextSet.create(); private final MutableContextSet extraContexts = MutableContextSet.create();
private Boolean value = true; private Boolean value = true;

View File

@ -32,9 +32,12 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
import me.lucko.luckperms.api.MetaUtils; import me.lucko.luckperms.api.MetaUtils;
import me.lucko.luckperms.api.Node; 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.constants.Patterns;
import me.lucko.luckperms.common.core.model.Group;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
/** /**
@ -118,7 +121,7 @@ public class NodeFactory {
return new NodeBuilder(other); 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")) { if (key.equalsIgnoreCase("prefix")) {
return makePrefixNode(100, value); return makePrefixNode(100, value);
} }
@ -129,15 +132,15 @@ public class NodeFactory {
return new NodeBuilder("meta." + MetaUtils.escapeCharacters(key) + "." + MetaUtils.escapeCharacters(value)); 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); 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)); 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)); return new NodeBuilder("suffix." + priority + "." + MetaUtils.escapeCharacters(suffix));
} }
@ -155,13 +158,7 @@ public class NodeFactory {
sb.append(node.getGroupName()); sb.append(node.getGroupName());
} }
if (node.isWorldSpecific()) { return appendContextToCommand(sb, node).toString();
sb.append(" ").append(node.getServer().get()).append(" ").append(node.getWorld().get());
} else if (node.isServerSpecific()) {
sb.append(" ").append(node.getServer().get());
}
return sb.toString();
} }
sb.append(node.isTemporary() ? "permission settemp " : "permission set "); sb.append(node.isTemporary() ? "permission settemp " : "permission set ");
@ -176,13 +173,28 @@ public class NodeFactory {
sb.append(" ").append(node.getExpiryUnixTime()); sb.append(" ").append(node.getExpiryUnixTime());
} }
if (node.isWorldSpecific()) { return appendContextToCommand(sb, node).toString();
sb.append(" ").append(node.getServer().get()).append(" ").append(node.getWorld().get());
} else if (node.isServerSpecific()) {
sb.append(" ").append(node.getServer().get());
} }
return sb.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());
}
}
ContextSet contexts = node.getContexts();
for (Map.Entry<String, String> context : contexts.toSet()) {
sb.append(" ").append(context.getKey()).append("=").append(context.getValue());
}
return sb;
} }
public static String escapeDelimiters(String s, String... delims) { 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) { 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(); 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);
}
} }

View File

@ -195,25 +195,20 @@ public class ImmutableNode implements Node {
throw new IllegalArgumentException("Empty permission"); throw new IllegalArgumentException("Empty permission");
} }
// standardize server/world values.
if (server != null) { if (server != null) {
server = server.toLowerCase(); server = server.toLowerCase();
} }
if (world != null) { if (world != null) {
world = world.toLowerCase(); world = world.toLowerCase();
} }
if (server != null && (server.equals("global") || server.equals(""))) { if (server != null && (server.equals("global") || server.equals(""))) {
server = null; server = null;
} }
if (world != null && (world.equals("global") || world.equals(""))) { if (world != null && (world.equals("global") || world.equals(""))) {
world = null; world = null;
} }
if (world != null && server == null) {
server = "global";
}
this.permission = NodeFactory.unescapeDelimiters(permission, "/", "-", "$", "(", ")", "=", ","); this.permission = NodeFactory.unescapeDelimiters(permission, "/", "-", "$", "(", ")", "=", ",");
this.value = value; this.value = value;
this.override = override; this.override = override;
@ -289,7 +284,7 @@ public class ImmutableNode implements Node {
@Override @Override
public boolean isServerSpecific() { public boolean isServerSpecific() {
return server != null && !server.equalsIgnoreCase("global"); return server != null;
} }
@Override @Override
@ -297,6 +292,16 @@ public class ImmutableNode implements Node {
return world != null; 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 @Override
public boolean isTemporary() { public boolean isTemporary() {
return expireAt != 0L; return expireAt != 0L;

View File

@ -29,6 +29,7 @@ import lombok.RequiredArgsConstructor;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder; import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.SortedSetMultimap; 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.caching.handlers.HolderReference;
import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.core.ContextSetComparator; 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.InheritanceInfo;
import me.lucko.luckperms.common.core.NodeComparator; import me.lucko.luckperms.common.core.NodeComparator;
import me.lucko.luckperms.common.core.NodeFactory; 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.ExtractedContexts;
import me.lucko.luckperms.common.utils.ImmutableLocalizedNode; import me.lucko.luckperms.common.utils.ImmutableLocalizedNode;
import me.lucko.luckperms.common.utils.NodeTools; 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.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -704,7 +704,7 @@ public abstract class PermissionHolder {
* @return a tristate * @return a tristate
*/ */
public Tristate hasPermission(Node node, boolean checkTransient) { 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; return Tristate.TRUE;
} }
@ -793,11 +793,10 @@ public abstract class PermissionHolder {
* Sets a permission node * Sets a permission node
* *
* @param node the node to set * @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) { if (hasPermission(node, false) != Tristate.UNDEFINED) {
throw new ObjectAlreadyHasException(); return DataMutateResult.ALREADY_HAS;
} }
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
@ -810,12 +809,7 @@ public abstract class PermissionHolder {
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after);
} return DataMutateResult.SUCCESS;
public void setPermissionUnchecked(Node node) {
try {
setPermission(node);
} catch (ObjectAlreadyHasException ignored) {}
} }
/** /**
@ -823,9 +817,8 @@ public abstract class PermissionHolder {
* @param node the node to set * @param node the node to set
* @param modifier the modifier to use for the operation * @param modifier the modifier to use for the operation
* @return the node that was actually set, respective of the modifier * @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<DataMutateResult, Node> setPermission(Node node, TemporaryModifier modifier) {
// If the node is temporary, we should take note of the modifier // If the node is temporary, we should take note of the modifier
if (node.isTemporary()) { if (node.isTemporary()) {
if (modifier == TemporaryModifier.ACCUMULATE) { if (modifier == TemporaryModifier.ACCUMULATE) {
@ -850,7 +843,7 @@ public abstract class PermissionHolder {
invalidateCache(); invalidateCache();
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeAdd(newNode, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeAdd(newNode, this, before, after);
return newNode; return Maps.immutableEntry(DataMutateResult.SUCCESS, newNode);
} }
} else if (modifier == TemporaryModifier.REPLACE) { } else if (modifier == TemporaryModifier.REPLACE) {
@ -874,7 +867,7 @@ public abstract class PermissionHolder {
invalidateCache(); invalidateCache();
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); 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. // Fallback to the normal handling.
setPermission(node); return Maps.immutableEntry(setPermission(node), node);
return node;
}
public void setPermissionUnchecked(Node node, TemporaryModifier modifier) {
try {
setPermission(node, modifier);
} catch (ObjectAlreadyHasException ignored) {}
} }
/** /**
* Sets a transient permission node * Sets a transient permission node
* *
* @param node the node to set * @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) { if (hasPermission(node, true) != Tristate.UNDEFINED) {
throw new ObjectAlreadyHasException(); return DataMutateResult.ALREADY_HAS;
} }
ImmutableSet<Node> before = ImmutableSet.copyOf(getTransientNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getTransientNodes().values());
@ -914,23 +899,17 @@ public abstract class PermissionHolder {
ImmutableSet<Node> after = ImmutableSet.copyOf(getTransientNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getTransientNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after);
} return DataMutateResult.SUCCESS;
public void setTransientPermissionUnchecked(Node node) {
try {
setTransientPermission(node);
} catch (ObjectAlreadyHasException ignored) {}
} }
/** /**
* Unsets a permission node * Unsets a permission node
* *
* @param node the node to unset * @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) { if (hasPermission(node, false) == Tristate.UNDEFINED) {
throw new ObjectLacksException(); return DataMutateResult.LACKS;
} }
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
@ -942,21 +921,15 @@ public abstract class PermissionHolder {
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after);
} return DataMutateResult.SUCCESS;
public void unsetPermissionUnchecked(Node node) {
try {
unsetPermission(node);
} catch (ObjectLacksException ignored) {}
} }
/** /**
* Unsets a permission node * Unsets a permission node
* *
* @param node the node to unset * @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<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
@ -967,21 +940,21 @@ public abstract class PermissionHolder {
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
if (before.size() == after.size()) { if (before.size() == after.size()) {
throw new ObjectLacksException(); return DataMutateResult.LACKS;
} }
plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after);
return DataMutateResult.SUCCESS;
} }
/** /**
* Unsets a transient permission node * Unsets a transient permission node
* *
* @param node the node to unset * @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) { if (hasPermission(node, true) == Tristate.UNDEFINED) {
throw new ObjectLacksException(); return DataMutateResult.LACKS;
} }
ImmutableSet<Node> before = ImmutableSet.copyOf(getTransientNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getTransientNodes().values());
@ -993,12 +966,7 @@ public abstract class PermissionHolder {
ImmutableSet<Node> after = ImmutableSet.copyOf(getTransientNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getTransientNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after); plugin.getApiProvider().getEventFactory().handleNodeRemove(node, this, before, after);
} return DataMutateResult.SUCCESS;
public void unsetTransientPermissionUnchecked(Node node) {
try {
unsetTransientPermission(node);
} catch (ObjectLacksException ignored) {}
} }
public boolean inheritsGroup(Group group) { 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); return group.getName().equalsIgnoreCase(this.getObjectName()) || hasPermission("group." + group.getName(), true, server, world);
} }
public void setInheritGroup(Group group) throws ObjectAlreadyHasException { public DataMutateResult setInheritGroup(Group group, ContextSet contexts) {
if (group.getName().equalsIgnoreCase(this.getObjectName())) { return setPermission(NodeFactory.newBuilder("group." + group.getName()).withExtraContext(contexts).build());
throw new ObjectAlreadyHasException();
} }
setPermission(NodeFactory.make("group." + group.getName(), true)); public DataMutateResult unsetInheritGroup(Group group, ContextSet contexts) {
} return unsetPermission(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));
} }
/** /**
@ -1098,32 +1002,10 @@ public abstract class PermissionHolder {
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
} }
public void clearNodes(String server) { public void clearNodes(ContextSet contextSet) {
String finalServer = Optional.ofNullable(server).orElse("global");
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
if (!nodes.values().removeIf(n -> n.getServer().orElse("global").equalsIgnoreCase(finalServer))) { nodes.removeAll(contextSet.makeImmutable());
return;
}
}
invalidateCache();
ImmutableSet<Node> 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<Node> 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;
}
} }
invalidateCache(); invalidateCache();
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
@ -1147,37 +1029,15 @@ public abstract class PermissionHolder {
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
} }
public void clearParents(String server, boolean giveDefault) { public void clearParents(ContextSet contextSet, boolean giveDefault) {
String finalServer = Optional.ofNullable(server).orElse("global");
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
boolean b = nodes.values().removeIf(n -> SortedSet<Node> nodes = this.nodes.get(contextSet.makeImmutable());
n.isGroupNode() && n.getServer().orElse("global").equalsIgnoreCase(finalServer) if (nodes == null) {
);
if (!b) {
return; return;
} }
}
if (this instanceof User && giveDefault) {
plugin.getUserManager().giveDefaultIfNeeded((User) this, false);
}
invalidateCache();
ImmutableSet<Node> after = ImmutableSet.copyOf(getNodes().values());
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
}
public void clearParents(String server, String world, boolean giveDefault) { boolean b = nodes.removeIf(Node::isGroupNode);
String finalServer = Optional.ofNullable(server).orElse("global");
String finalWorld = Optional.ofNullable(world).orElse("null");
ImmutableSet<Node> 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)
);
if (!b) { if (!b) {
return; return;
} }
@ -1203,15 +1063,15 @@ public abstract class PermissionHolder {
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
} }
public void clearMeta(String server) { public void clearMeta(ContextSet contextSet) {
String finalServer = Optional.ofNullable(server).orElse("global");
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
boolean b = nodes.values().removeIf(n -> SortedSet<Node> nodes = this.nodes.get(contextSet.makeImmutable());
(n.isMeta() || n.isPrefix() || n.isSuffix()) && if (nodes == null) {
n.getServer().orElse("global").equalsIgnoreCase(finalServer) return;
); }
boolean b = nodes.removeIf(n -> n.isMeta() || n.isPrefix() || n.isSuffix());
if (!b) { if (!b) {
return; return;
} }
@ -1221,18 +1081,10 @@ public abstract class PermissionHolder {
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
} }
public void clearMeta(String server, String world) { public void clearMetaKeys(String key, boolean temp) {
String finalServer = Optional.ofNullable(server).orElse("global");
String finalWorld = Optional.ofNullable(world).orElse("null");
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
boolean b = nodes.values().removeIf(n -> boolean b = this.nodes.values().removeIf(n -> n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key));
(n.isMeta() || n.isPrefix() || n.isSuffix()) && (
n.getServer().orElse("global").equalsIgnoreCase(finalServer) &&
n.getWorld().orElse("null").equalsIgnoreCase(finalWorld)
)
);
if (!b) { if (!b) {
return; return;
} }
@ -1242,17 +1094,16 @@ public abstract class PermissionHolder {
plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after); plugin.getApiProvider().getEventFactory().handleNodeClear(this, before, after);
} }
public void clearMetaKeys(String key, String server, String world, boolean temp) { public void clearMetaKeys(String key, ContextSet contextSet, boolean temp) {
String finalServer = Optional.ofNullable(server).orElse("global");
String finalWorld = Optional.ofNullable(world).orElse("null");
ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values()); ImmutableSet<Node> before = ImmutableSet.copyOf(getNodes().values());
synchronized (nodes) { synchronized (nodes) {
boolean b = nodes.values().removeIf(n ->
n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key) && SortedSet<Node> nodes = this.nodes.get(contextSet.makeImmutable());
n.getServer().orElse("global").equalsIgnoreCase(finalServer) && if (nodes == null) {
n.getWorld().orElse("null").equalsIgnoreCase(finalWorld) return;
); }
boolean b = nodes.removeIf(n -> n.isMeta() && (n.isTemporary() == temp) && n.getMeta().getKey().equalsIgnoreCase(key));
if (!b) { if (!b) {
return; return;
} }
@ -1321,18 +1172,6 @@ public abstract class PermissionHolder {
return weight; 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<String> getGroupNames() {
return mergePermissionsToList().stream()
.filter(Node::isGroupNode)
.map(Node::getGroupName)
.collect(Collectors.toList());
}
public Set<HolderReference> getGroupReferences() { public Set<HolderReference> getGroupReferences() {
return mergePermissionsToList().stream() return mergePermissionsToList().stream()
.filter(Node::isGroupNode) .filter(Node::isGroupNode)
@ -1341,43 +1180,4 @@ public abstract class PermissionHolder {
.map(GroupReference::of) .map(GroupReference::of)
.collect(Collectors.toSet()); .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<String> 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<String> 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<String> getLocalGroups(String server) {
return mergePermissionsToList().stream()
.filter(Node::isGroupNode)
.filter(n -> n.shouldApplyOnServer(server, false, true))
.map(Node::getGroupName)
.collect(Collectors.toList());
}
} }

View File

@ -89,11 +89,11 @@ public class Rule {
// The holder meets all of the requirements of this rule. // The holder meets all of the requirements of this rule.
for (String s : toTake) { for (String s : toTake) {
user.unsetPermissionUnchecked(NodeFactory.fromSerialisedNode(s, true)); user.unsetPermission(NodeFactory.fromSerialisedNode(s, true));
} }
for (String s : toGive) { for (String s : toGive) {
user.setPermissionUnchecked(NodeFactory.fromSerialisedNode(s, true)); user.setPermission(NodeFactory.fromSerialisedNode(s, true));
} }
if (setPrimaryGroup != null) { if (setPrimaryGroup != null) {

View File

@ -42,7 +42,7 @@ public class GenericUserManager extends AbstractManager<UserIdentifier, User> im
if (user.getPrimaryGroup().getStoredValue() != null && !user.getPrimaryGroup().getStoredValue().isEmpty()) { if (user.getPrimaryGroup().getStoredValue() != null && !user.getPrimaryGroup().getStoredValue().isEmpty()) {
for (Node node : user.getNodes().values()) { for (Node node : user.getNodes().values()) {
if (node.isServerSpecific() || node.isWorldSpecific()) { if (node.hasSpecificContext()) {
continue; continue;
} }
@ -58,7 +58,7 @@ public class GenericUserManager extends AbstractManager<UserIdentifier, User> im
} }
user.getPrimaryGroup().setStoredValue("default"); user.getPrimaryGroup().setStoredValue("default");
user.setPermissionUnchecked(NodeFactory.make("group.default")); user.setPermission(NodeFactory.make("group.default"));
if (save) { if (save) {
plugin.getStorage().saveUser(user); plugin.getStorage().saveUser(user);

View File

@ -27,15 +27,20 @@ import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.ToString; import lombok.ToString;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSetMultimap;
import com.google.gson.Gson; 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.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.Collection;
import java.util.List;
import java.util.Map; import java.util.Map;
@Getter @Getter
@ -44,7 +49,6 @@ import java.util.Map;
@AllArgsConstructor(staticName = "of") @AllArgsConstructor(staticName = "of")
public class NodeDataHolder { public class NodeDataHolder {
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
private static final Type CONTEXT_TYPE = new TypeToken<Map<String, Collection<String>>>(){}.getType();
public static NodeDataHolder fromNode(Node node) { public static NodeDataHolder fromNode(Node node) {
return NodeDataHolder.of( 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) { public static NodeDataHolder of(String permission, boolean value, String server, String world, long expiry, String contexts) {
Map<String, Collection<String>> deserializedContexts = GSON.fromJson(contexts, CONTEXT_TYPE); JsonObject context = GSON.fromJson(contexts, JsonObject.class);
ImmutableSetMultimap.Builder<String, String> map = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<String, String> map = ImmutableSetMultimap.builder();
for (Map.Entry<String, Collection<String>> e : deserializedContexts.entrySet()) { for (Map.Entry<String, JsonElement> e : context.entrySet()) {
map.putAll(e.getKey(), e.getValue()); 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()); return new NodeDataHolder(permission, value, server, world, expiry, map.build());
} }
@ -75,11 +86,29 @@ public class NodeDataHolder {
private final ImmutableSetMultimap<String, String> contexts; private final ImmutableSetMultimap<String, String> contexts;
public String serialiseContext() { public String serialiseContext() {
return GSON.toJson(getContexts().asMap()); JsonObject context = new JsonObject();
ImmutableMap<String, Collection<String>> map = getContexts().asMap();
map.forEach((key, value) -> {
List<String> 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() { public Node toNode() {
NodeBuilder builder = new NodeBuilder(permission); Node.Builder builder = NodeFactory.newBuilder(permission);
builder.setValue(value); builder.setValue(value);
builder.setServer(server); builder.setServer(server);
builder.setWorld(world); builder.setWorld(world);

View File

@ -64,7 +64,7 @@ public class SpongeSenderFactory extends SenderFactory<CommandSource> {
@Override @Override
protected void sendMessage(CommandSource source, FancyMessage message) { protected void sendMessage(CommandSource source, FancyMessage message) {
try { try {
source.sendMessage(TextSerializers.JSON.deserialize(message.toJSONString())); source.sendMessage(TextSerializers.JSON.deserialize(message.exportToJson()));
} catch (Exception e) { } catch (Exception e) {
sendMessage(source, message.toOldMessageFormat()); sendMessage(source, message.toOldMessageFormat());
} }

View File

@ -26,7 +26,6 @@ import lombok.experimental.UtilityClass;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import me.lucko.luckperms.common.commands.impl.migration.MigrationUtils; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.PermissionHolder; import me.lucko.luckperms.common.core.model.PermissionHolder;
@ -63,7 +62,7 @@ public class SpongeMigrationUtils {
String world = extractedContexts.getWorld(); String world = extractedContexts.getWorld();
for (Map.Entry<String, Boolean> perm : e.getValue().entrySet()) { for (Map.Entry<String, Boolean> 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<String, String> opt : e.getValue().entrySet()) { for (Map.Entry<String, String> opt : e.getValue().entrySet()) {
if (opt.getKey().equalsIgnoreCase("prefix")) { 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")) { } 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 { } 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. 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());
} }
} }
} }

View File

@ -34,7 +34,6 @@ import me.lucko.luckperms.api.Tristate;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import me.lucko.luckperms.api.context.ImmutableContextSet; import me.lucko.luckperms.api.context.ImmutableContextSet;
import me.lucko.luckperms.common.caching.MetaAccumulator; 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.NodeFactory;
import me.lucko.luckperms.common.core.model.Group; import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.PermissionHolder; 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)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_PERMISSION)) {
if (tristate == Tristate.UNDEFINED) { if (tristate == Tristate.UNDEFINED) {
// Unset // Unset
Node node = new NodeBuilder(permission).withExtraContext(contexts).build(); Node node = NodeFactory.newBuilder(permission).withExtraContext(contexts).build();
if (enduring) { if (enduring) {
holder.unsetPermissionUnchecked(node); holder.unsetPermission(node);
} else { } else {
holder.unsetTransientPermissionUnchecked(node); holder.unsetTransientPermission(node);
} }
objectSave(holder); objectSave(holder);
return true; 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. // Workaround: unset the inverse, to allow false -> true, true -> false overrides.
if (enduring) { if (enduring) {
holder.unsetPermissionUnchecked(node); holder.unsetPermission(node);
} else { } else {
holder.unsetTransientPermissionUnchecked(node); holder.unsetTransientPermission(node);
} }
if (enduring) { if (enduring) {
holder.setPermissionUnchecked(node); holder.setPermission(node);
} else { } else {
holder.setTransientPermissionUnchecked(node); holder.setTransientPermission(node);
} }
objectSave(holder); objectSave(holder);
@ -188,11 +187,11 @@ public class LuckPermsSubjectData implements LPSubjectData {
LPSubject permsSubject = subject.resolve(service); LPSubject permsSubject = subject.resolve(service);
if (enduring) { if (enduring) {
holder.setPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) holder.setPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier())
.withExtraContext(contexts) .withExtraContext(contexts)
.build()); .build());
} else { } else {
holder.setTransientPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) holder.setTransientPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier())
.withExtraContext(contexts) .withExtraContext(contexts)
.build()); .build());
} }
@ -211,11 +210,11 @@ public class LuckPermsSubjectData implements LPSubjectData {
LPSubject permsSubject = subject.resolve(service); LPSubject permsSubject = subject.resolve(service);
if (enduring) { if (enduring) {
holder.unsetPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) holder.unsetPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier())
.withExtraContext(contexts) .withExtraContext(contexts)
.build()); .build());
} else { } else {
holder.unsetTransientPermissionUnchecked(new NodeBuilder("group." + permsSubject.getIdentifier()) holder.unsetTransientPermission(NodeFactory.newBuilder("group." + permsSubject.getIdentifier())
.withExtraContext(contexts) .withExtraContext(contexts)
.build()); .build());
} }
@ -337,9 +336,9 @@ public class LuckPermsSubjectData implements LPSubjectData {
priority += 10; priority += 10;
if (enduring) { 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 { } 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 { } else {
@ -352,9 +351,9 @@ public class LuckPermsSubjectData implements LPSubjectData {
toRemove.forEach(makeUnsetConsumer(enduring)); toRemove.forEach(makeUnsetConsumer(enduring));
if (enduring) { if (enduring) {
holder.setPermissionUnchecked(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build()); holder.setPermission(NodeFactory.makeMetaNode(key, value).withExtraContext(context).build());
} else { } 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<Node> makeUnsetConsumer(boolean enduring) { private Consumer<Node> makeUnsetConsumer(boolean enduring) {
return n -> { return n -> {
if (enduring) { if (enduring) {
holder.unsetPermissionUnchecked(n); holder.unsetPermission(n);
} else { } else {
holder.unsetTransientPermissionUnchecked(n); holder.unsetTransientPermission(n);
} }
}; };
} }