net.luckperms.api.node.types.InheritanceNode Java Examples

The following examples show how to use net.luckperms.api.node.types.InheritanceNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LuckPermsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 8 votes vote down vote up
@Override
public boolean addToGroup(OfflinePlayer player, String group) {
    Group newGroup = luckPerms.getGroupManager().getGroup(group);
    if (newGroup == null) {
        return false;
    }

    String playerName = player.getName();
    if (playerName == null) {
        return false;
    }
    User user = luckPerms.getUserManager().getUser(playerName);
    if (user == null) {
        return false;
    }

    InheritanceNode node = InheritanceNode.builder(group).build();
    DataMutateResult result = user.data().add(node);
    if (result == DataMutateResult.FAIL) {
        return false;
    }

    luckPerms.getUserManager().saveUser(user);
    return true;
}
 
Example #2
Source File: ParentInfo.java    From LuckPerms with MIT License 6 votes vote down vote up
private static Consumer<ComponentBuilder<? ,?>> makeFancy(PermissionHolder holder, String label, InheritanceNode node) {
    HoverEvent hoverEvent = HoverEvent.showText(TextUtils.fromLegacy(TextUtils.joinNewline(
            "&3> &f" + node.getGroupName(),
            " ",
            "&7Click to remove this parent from " + holder.getPlainDisplayName()
    ), TextUtils.AMPERSAND_CHAR));

    String id = holder.getType() == HolderType.GROUP ? holder.getObjectName() : holder.getPlainDisplayName();
    boolean explicitGlobalContext = !holder.getPlugin().getConfiguration().getContextsFile().getDefaultContexts().isEmpty();
    String command = "/" + label + " " + NodeCommandFactory.undoCommand(node, id, holder.getType(), explicitGlobalContext);
    ClickEvent clickEvent = ClickEvent.suggestCommand(command);

    return component -> {
        component.hoverEvent(hoverEvent);
        component.clickEvent(clickEvent);
    };
}
 
Example #3
Source File: NodeMap.java    From LuckPerms with MIT License 6 votes vote down vote up
public void forEach(QueryOptions filter, Consumer<? super Node> consumer) {
    for (Map.Entry<ImmutableContextSet, SortedSet<Node>> e : this.map.entrySet()) {
        if (!filter.satisfies(e.getKey(), defaultSatisfyMode())) {
            continue;
        }

        if (normalNodesExcludeTest(filter, e.getKey())) {
            if (inheritanceNodesIncludeTest(filter, e.getKey())) {
                // only copy inheritance nodes.
                SortedSet<InheritanceNode> inheritanceNodes = this.inheritanceMap.get(e.getKey());
                if (inheritanceNodes != null) {
                    inheritanceNodes.forEach(consumer);
                }
            }
        } else {
            e.getValue().forEach(consumer);
        }
    }
}
 
Example #4
Source File: NodeMap.java    From LuckPerms with MIT License 6 votes vote down vote up
public void copyTo(Collection<? super Node> collection, QueryOptions filter) {
    for (Map.Entry<ImmutableContextSet, SortedSet<Node>> e : this.map.entrySet()) {
        if (!filter.satisfies(e.getKey(), defaultSatisfyMode())) {
            continue;
        }

        if (normalNodesExcludeTest(filter, e.getKey())) {
            if (inheritanceNodesIncludeTest(filter, e.getKey())) {
                // only copy inheritance nodes.
                SortedSet<InheritanceNode> inheritanceNodes = this.inheritanceMap.get(e.getKey());
                if (inheritanceNodes != null) {
                    collection.addAll(inheritanceNodes);
                }
            }
        } else {
            collection.addAll(e.getValue());
        }
    }
}
 
Example #5
Source File: AbstractUserManager.java    From LuckPerms with MIT License 6 votes vote down vote up
/**
 * Check whether the user's state indicates that they should be persisted to storage.
 *
 * @param user the user to check
 * @return true if the user should be saved
 */
@Override
public boolean shouldSave(User user) {
    ImmutableCollection<Node> nodes = user.normalData().immutable().values();
    if (nodes.size() != 1) {
        return true;
    }

    Node onlyNode = nodes.iterator().next();
    if (!(onlyNode instanceof InheritanceNode)) {
        return true;
    }

    if (onlyNode.hasExpiry() || !onlyNode.getContexts().isEmpty()) {
        return true;
    }

    if (!((InheritanceNode) onlyNode).getGroupName().equalsIgnoreCase(GroupManager.DEFAULT_GROUP_NAME)) {
        // The user's only node is not the default group one.
        return true;
    }


    // Not in the default primary group
    return !user.getPrimaryGroup().getStoredValue().orElse(GroupManager.DEFAULT_GROUP_NAME).equalsIgnoreCase(GroupManager.DEFAULT_GROUP_NAME);
}
 
Example #6
Source File: NodeMap.java    From LuckPerms with MIT License 6 votes vote down vote up
void add(Node node) {
    ImmutableContextSet context = node.getContexts();
    Node n = localise(node);

    SortedSet<Node> nodesInContext = this.map.computeIfAbsent(context, VALUE_SET_SUPPLIER);
    nodesInContext.removeIf(e -> e.equals(node, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE));
    nodesInContext.add(n);

    if (n instanceof InheritanceNode) {
        SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.computeIfAbsent(context, INHERITANCE_VALUE_SET_SUPPLIER);
        inheritanceNodesInContext.removeIf(e -> e.equals(node, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE));
        if (n.getValue()) {
            inheritanceNodesInContext.add((InheritanceNode) n);
        }
    }
}
 
Example #7
Source File: PrimaryGroupHolder.java    From LuckPerms with MIT License 6 votes vote down vote up
@Override
public String calculateValue(QueryOptions queryOptions) {
    Set<Group> groups = new LinkedHashSet<>();
    for (InheritanceNode node : this.user.getOwnInheritanceNodes(queryOptions)) {
        Group group = this.user.getPlugin().getGroupManager().getIfLoaded(node.getGroupName());
        if (group != null) {
            groups.add(group);
        }
    }

    Group bestGroup = null;
    int best = 0;

    for (Group g : groups) {
        int weight = g.getWeight().orElse(0);
        if (bestGroup == null || weight > best) {
            bestGroup = g;
            best = weight;
        }
    }

    return bestGroup == null ? super.calculateValue(queryOptions) : bestGroup.getName();
}
 
Example #8
Source File: NodeMap.java    From LuckPerms with MIT License 6 votes vote down vote up
boolean removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
    ImmutableContextSet context = contextSet.immutableCopy();

    boolean success = false;

    SortedSet<Node> nodesInContext = this.map.get(context);
    if (nodesInContext != null) {
        success = nodesInContext.removeIf(predicate);
    }

    SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.get(context);
    if (inheritanceNodesInContext != null) {
        inheritanceNodesInContext.removeIf(predicate);
    }

    return success;
}
 
Example #9
Source File: LuckPermsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isInGroup(OfflinePlayer player, String group) {
    String playerName = player.getName();
    if (playerName == null) {
        return false;
    }
    User user = luckPerms.getUserManager().getUser(playerName);
    if (user == null) {
        logger.warning("LuckPermsHandler: tried to check group for offline user "
            + player.getName() + " but it isn't loaded!");
        return false;
    }

    InheritanceNode inheritanceNode = InheritanceNode.builder(group).build();
    return user.data().contains(inheritanceNode, NodeEqualityPredicate.EXACT).asBoolean();
}
 
Example #10
Source File: LuckPermsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean removeFromGroup(OfflinePlayer player, String group) {
    String playerName = player.getName();
    if (playerName == null) {
        return false;
    }
    User user = luckPerms.getUserManager().getUser(playerName);
    if (user == null) {
        logger.warning("LuckPermsHandler: tried to remove group for offline user "
            + player.getName() + " but it isn't loaded!");
        return false;
    }

    InheritanceNode groupNode = InheritanceNode.builder(group).build();
    boolean result = user.data().remove(groupNode) != DataMutateResult.FAIL;

    luckPerms.getUserManager().saveUser(user);
    return result;
}
 
Example #11
Source File: NodeMap.java    From LuckPerms with MIT License 5 votes vote down vote up
boolean auditTemporaryNodes(@Nullable Set<? super Node> removed) {
    boolean work = false;

    for (SortedSet<Node> valueSet : this.map.values()) {
        Iterator<Node> it = valueSet.iterator();
        while (it.hasNext()) {
            Node entry = it.next();
            if (!entry.hasExpired()) {
                continue;
            }

            // remove
            if (removed != null) {
                removed.add(entry);
            }
            if (entry instanceof InheritanceNode && entry.getValue()) {
                SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.get(entry.getContexts());
                if (inheritanceNodesInContext != null) {
                    inheritanceNodesInContext.remove(entry);
                }
            }
            it.remove();
            work = true;
        }
    }

    return work;
}
 
Example #12
Source File: LuckPermsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<String> getGroups(OfflinePlayer player) {
    String playerName = player.getName();
    if (playerName == null) {
        return Collections.emptyList();
    }
    User user = luckPerms.getUserManager().getUser(playerName);
    if (user == null) {
        logger.warning("LuckPermsHandler: tried to get groups for offline user "
            + player.getName() + " but it isn't loaded!");
        return Collections.emptyList();
    }

    return user.getDistinctNodes().stream()
        .filter(node -> node instanceof InheritanceNode)
        .map(node -> (InheritanceNode) node)
        .map(node -> luckPerms.getGroupManager().getGroup(node.getGroupName()))
        .filter(Objects::nonNull)
        .sorted((o1, o2) -> {
            if (o1.getName().equals(user.getPrimaryGroup()) || o2.getName().equals(user.getPrimaryGroup())) {
                return o1.getName().equals(user.getPrimaryGroup()) ? 1 : -1;
            }

            int i = Integer.compare(o2.getWeight().orElse(0), o1.getWeight().orElse(0));
            return i != 0 ? i : o1.getName().compareToIgnoreCase(o2.getName());
        })
        .map(Group::getName)
        .collect(Collectors.toList());
}
 
Example #13
Source File: NodeMap.java    From LuckPerms with MIT License 5 votes vote down vote up
private void removeExact(Node node) {
    ImmutableContextSet context = node.getContexts();
    SortedSet<Node> nodesInContext = this.map.get(context);
    if (nodesInContext != null) {
        nodesInContext.remove(node);
    }

    if (node instanceof InheritanceNode && node.getValue()) {
        SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.get(context);
        if (inheritanceNodesInContext != null) {
            inheritanceNodesInContext.remove(node);
        }
    }
}
 
Example #14
Source File: PermissionHolder.java    From LuckPerms with MIT License 5 votes vote down vote up
public List<InheritanceNode> getOwnInheritanceNodes(QueryOptions queryOptions) {
    List<InheritanceNode> nodes = new ArrayList<>();
    for (DataType dataType : queryOrder(queryOptions)) {
        getData(dataType).copyInheritanceNodesTo(nodes, queryOptions);
    }
    return nodes;
}
 
Example #15
Source File: NodeMap.java    From LuckPerms with MIT License 5 votes vote down vote up
void remove(Node node) {
    ImmutableContextSet context = node.getContexts();
    SortedSet<Node> nodesInContext = this.map.get(context);
    if (nodesInContext != null) {
        nodesInContext.removeIf(e -> e.equals(node, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE));
    }

    if (node instanceof InheritanceNode) {
        SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.get(context);
        if (inheritanceNodesInContext != null) {
            inheritanceNodesInContext.removeIf(e -> e.equals(node, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE));
        }
    }
}
 
Example #16
Source File: PermissionHolder.java    From LuckPerms with MIT License 5 votes vote down vote up
public Tristate hasNode(DataType type, Node node, NodeEqualityPredicate equalityPredicate) {
    if (this.getType() == HolderType.GROUP && node instanceof InheritanceNode && ((InheritanceNode) node).getGroupName().equalsIgnoreCase(getObjectName())) {
        return Tristate.TRUE;
    }

    return getData(type).immutable().values().stream()
            .filter(equalityPredicate.equalTo(node))
            .findFirst()
            .map(n -> Tristate.of(n.getValue())).orElse(Tristate.UNDEFINED);
}
 
Example #17
Source File: NodeMap.java    From LuckPerms with MIT License 5 votes vote down vote up
public void copyInheritanceNodesTo(Collection<? super InheritanceNode> collection, QueryOptions filter) {
    for (Map.Entry<ImmutableContextSet, SortedSet<InheritanceNode>> e : this.inheritanceMap.entrySet()) {
        if (!filter.satisfies(e.getKey(), defaultSatisfyMode())) {
            continue;
        }

        if (inheritanceNodesIncludeTest(filter, e.getKey())) {
            collection.addAll(e.getValue());
        }
    }
}
 
Example #18
Source File: LuckPermsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean setGroup(OfflinePlayer player, String group) {
    String playerName = player.getName();
    if (playerName == null) {
        return false;
    }
    User user = luckPerms.getUserManager().getUser(playerName);
    if (user == null) {
        logger.warning("LuckPermsHandler: tried to set group for offline user "
            + player.getName() + " but it isn't loaded!");
        return false;
    }
    InheritanceNode groupNode = InheritanceNode.builder(group).build();
    DataMutateResult result = user.data().add(groupNode);
    if (result == DataMutateResult.FAIL) {
        return false;
    }
    user.data().clear(node -> {
        if (!(node instanceof InheritanceNode)) {
            return false;
        }
        InheritanceNode inheritanceNode = (InheritanceNode) node;
        return !inheritanceNode.equals(groupNode);
    });

    luckPerms.getUserManager().saveUser(user);
    return true;
}
 
Example #19
Source File: GroupListMembers.java    From LuckPerms with MIT License 5 votes vote down vote up
private static Consumer<ComponentBuilder<? ,?>> makeFancy(String holderName, HolderType holderType, String label, NodeEntry<?, ?> perm, LuckPermsPlugin plugin) {
    HoverEvent hoverEvent = HoverEvent.showText(TextUtils.fromLegacy(TextUtils.joinNewline(
            "&3> &b" + ((InheritanceNode) perm.getNode()).getGroupName(),
            " ",
            "&7Click to remove this parent from " + holderName
    ), TextUtils.AMPERSAND_CHAR));

    boolean explicitGlobalContext = !plugin.getConfiguration().getContextsFile().getDefaultContexts().isEmpty();
    String command = "/" + label + " " + NodeCommandFactory.undoCommand(perm.getNode(), holderName, holderType, explicitGlobalContext);
    ClickEvent clickEvent = ClickEvent.suggestCommand(command);

    return component -> {
        component.hoverEvent(hoverEvent);
        component.clickEvent(clickEvent);
    };
}
 
Example #20
Source File: GroupListMembers.java    From LuckPerms with MIT License 5 votes vote down vote up
private static <T extends Comparable<T>> void sendResult(Sender sender, List<NodeEntry<T, InheritanceNode>> results, Function<T, String> lookupFunction, Message headerMessage, HolderType holderType, String label, int page) {
    results = new ArrayList<>(results);
    results.sort(NodeEntryComparator.normal());

    int pageIndex = page - 1;
    List<List<NodeEntry<T, InheritanceNode>>> pages = Iterators.divideIterable(results, 15);

    if (pageIndex < 0 || pageIndex >= pages.size()) {
        page = 1;
        pageIndex = 0;
    }

    List<NodeEntry<T, InheritanceNode>> content = pages.get(pageIndex);

    List<Map.Entry<String, NodeEntry<T, InheritanceNode>>> mappedContent = content.stream()
            .map(hp -> Maps.immutableEntry(lookupFunction.apply(hp.getHolder()), hp))
            .collect(Collectors.toList());

    // send header
    headerMessage.send(sender, page, pages.size(), results.size());

    for (Map.Entry<String, NodeEntry<T, InheritanceNode>> ent : mappedContent) {
        String s = "&3> &b" + ent.getKey() + " " + getNodeExpiryString(ent.getValue().getNode()) + MessageUtils.getAppendableNodeContextString(sender.getPlugin().getLocaleManager(), ent.getValue().getNode());
        TextComponent message = TextUtils.fromLegacy(s, TextUtils.AMPERSAND_CHAR).toBuilder().applyDeep(makeFancy(ent.getKey(), holderType, label, ent.getValue(), sender.getPlugin())).build();
        sender.sendMessage(message);
    }
}
 
Example #21
Source File: PermissionHolderSubjectData.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ImmutableList<LPSubjectReference> getParents(ImmutableContextSet contexts) {
    ImmutableList.Builder<LPSubjectReference> builder = ImmutableList.builder();
    for (InheritanceNode n : this.holder.getData(this.type).immutableInheritance().get(contexts)) {
        builder.add(this.service.getGroupSubjects().loadSubject(n.getGroupName()).join().toReference());
    }
    return builder.build();
}
 
Example #22
Source File: NodeMap.java    From LuckPerms with MIT License 4 votes vote down vote up
public SortedSet<InheritanceNode> inheritanceAsSortedSet() {
    SortedSet<InheritanceNode> set = new TreeSet<>(NodeWithContextComparator.reverse());
    copyInheritanceNodesTo(set, QueryOptionsImpl.DEFAULT_NON_CONTEXTUAL);
    return set;
}
 
Example #23
Source File: NodeMap.java    From LuckPerms with MIT License 4 votes vote down vote up
public LinkedHashSet<InheritanceNode> inheritanceAsSet() {
    LinkedHashSet<InheritanceNode> set = new LinkedHashSet<>();
    copyInheritanceNodesTo(set, QueryOptionsImpl.DEFAULT_NON_CONTEXTUAL);
    return set;
}
 
Example #24
Source File: NodeMap.java    From LuckPerms with MIT License 4 votes vote down vote up
public ImmutableSetMultimap<ImmutableContextSet, InheritanceNode> immutableInheritance() {
    return this.inheritanceMapCache.get();
}
 
Example #25
Source File: AbstractUserManager.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public boolean giveDefaultIfNeeded(User user, boolean save) {
    boolean work = false;

    // check that they are actually a member of their primary group, otherwise remove it
    if (this.plugin.getConfiguration().get(ConfigKeys.PRIMARY_GROUP_CALCULATION_METHOD).equals("stored")) {
        String primaryGroup = user.getCachedData().getMetaData(this.plugin.getConfiguration().get(ConfigKeys.GLOBAL_QUERY_OPTIONS)).getPrimaryGroup(MetaCheckEvent.Origin.INTERNAL);
        boolean memberOfPrimaryGroup = false;

        for (InheritanceNode node : user.normalData().immutableInheritance().get(ImmutableContextSetImpl.EMPTY)) {
            if (node.getGroupName().equalsIgnoreCase(primaryGroup)) {
                memberOfPrimaryGroup = true;
                break;
            }
        }

        // need to find a new primary group for the user.
        if (!memberOfPrimaryGroup) {
            String group = user.normalData().immutableInheritance().get(ImmutableContextSetImpl.EMPTY).stream()
                    .findFirst()
                    .map(InheritanceNode::getGroupName)
                    .orElse(null);

            // if the group is null, it'll be resolved in the next step
            if (group != null) {
                user.getPrimaryGroup().setStoredValue(group);
                work = true;
            }
        }
    }

    // check that all users are member of at least one group
    boolean hasGroup = false;
    if (user.getPrimaryGroup().getStoredValue().isPresent()) {
        hasGroup = !user.normalData().immutableInheritance().get(ImmutableContextSetImpl.EMPTY).isEmpty();
    }

    if (!hasGroup) {
        user.getPrimaryGroup().setStoredValue(GroupManager.DEFAULT_GROUP_NAME);
        user.setNode(DataType.NORMAL, Inheritance.builder(GroupManager.DEFAULT_GROUP_NAME).build(), false);
        work = true;
    }

    if (work && save) {
        this.plugin.getStorage().saveUser(user);
    }

    return work;
}
 
Example #26
Source File: Track.java    From LuckPerms with MIT License 4 votes vote down vote up
public DemotionResult demote(User user, ContextSet context, Predicate<String> previousGroupPermissionChecker, @Nullable Sender sender, boolean removeFromFirst) {
    if (getSize() <= 1) {
        throw new IllegalStateException("Track contains one or fewer groups, unable to demote");
    }

    // find all groups that are inherited by the user in the exact contexts given and applicable to this track
    List<InheritanceNode> nodes = user.normalData().immutableInheritance().get(context.immutableCopy()).stream()
            .filter(Node::getValue)
            .filter(node -> containsGroup(node.getGroupName()))
            .distinct()
            .collect(Collectors.toList());

    if (nodes.isEmpty()) {
        return DemotionResults.notOnTrack();
    }

    if (nodes.size() != 1) {
        return DemotionResults.ambiguousCall();
    }

    InheritanceNode oldNode = nodes.get(0);
    String old = oldNode.getGroupName();
    String previous = getPrevious(old);

    if (!previousGroupPermissionChecker.test(oldNode.getGroupName())) {
        return DemotionResults.undefinedFailure();
    }

    if (previous == null) {
        if (!removeFromFirst) {
            return DemotionResults.removedFromFirst(null);
        }

        user.unsetNode(DataType.NORMAL, oldNode);
        this.plugin.getEventDispatcher().dispatchUserDemote(user, this, old, null, sender);
        return DemotionResults.removedFromFirst(old);
    }

    Group previousGroup = this.plugin.getGroupManager().getIfLoaded(previous);
    if (previousGroup == null) {
        return DemotionResults.malformedTrack(previous);
    }

    user.unsetNode(DataType.NORMAL, oldNode);
    user.setNode(DataType.NORMAL, Inheritance.builder(previousGroup.getName()).withContext(context).build(), true);

    if (context.isEmpty() && user.getPrimaryGroup().getStoredValue().orElse(GroupManager.DEFAULT_GROUP_NAME).equalsIgnoreCase(old)) {
        user.getPrimaryGroup().setStoredValue(previousGroup.getName());
    }

    this.plugin.getEventDispatcher().dispatchUserDemote(user, this, old, previousGroup.getName(), sender);
    return DemotionResults.success(old, previousGroup.getName());
}
 
Example #27
Source File: ApiNodeBuilderRegistry.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public InheritanceNode.@NonNull Builder forInheritance() {
    return Inheritance.builder();
}
 
Example #28
Source File: PermissionUnsetTemp.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder target, ArgumentList args, String label, CommandPermission permission) throws CommandException {
    if (ArgumentPermissions.checkModifyPerms(plugin, sender, permission, target)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    String node = args.get(0);
    Duration duration = args.getDurationOrDefault(1, null);
    int fromIndex = duration == null ? 1 : 2;
    MutableContextSet context = args.getContextOrDefault(fromIndex, plugin);

    if (ArgumentPermissions.checkContext(plugin, sender, permission, context) ||
            ArgumentPermissions.checkGroup(plugin, sender, target, context) ||
            ArgumentPermissions.checkArguments(plugin, sender, permission, node)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    Node builtNode = NodeBuilders.determineMostApplicable(node).expiry(10L).withContext(context).build();

    if (builtNode instanceof InheritanceNode) {
        if (ArgumentPermissions.checkGroup(plugin, sender, ((InheritanceNode) builtNode).getGroupName(), context)) {
            Message.COMMAND_NO_PERMISSION.send(sender);
            return CommandResult.NO_PERMISSION;
        }
    }

    DataMutateResult.WithMergedNode result = target.unsetNode(DataType.NORMAL, builtNode, duration);
    if (result.getResult().wasSuccessful()) {
        Node mergedNode = result.getMergedNode();
        //noinspection ConstantConditions
        if (mergedNode != null) {
            Message.UNSET_TEMP_PERMISSION_SUBTRACT_SUCCESS.send(sender,
                    mergedNode.getKey(),
                    mergedNode.getValue(),
                    target.getFormattedDisplayName(),
                    DurationFormatter.LONG.format(mergedNode.getExpiryDuration()),
                    MessageUtils.contextSetToString(plugin.getLocaleManager(), context),
                    DurationFormatter.LONG.format(duration)
            );

            LoggedAction.build().source(sender).target(target)
                    .description("permission", "unsettemp", node, duration, context)
                    .build().submit(plugin, sender);
        } else {
            Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, target.getFormattedDisplayName(), MessageUtils.contextSetToString(plugin.getLocaleManager(), context));

            LoggedAction.build().source(sender).target(target)
                    .description("permission", "unsettemp", node, context)
                    .build().submit(plugin, sender);
        }

        StorageAssistant.save(target, sender, plugin);
        return CommandResult.SUCCESS;
    } else {
        Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, target.getFormattedDisplayName(), node, MessageUtils.contextSetToString(plugin.getLocaleManager(), context));
        return CommandResult.STATE_ERROR;
    }
}
 
Example #29
Source File: PermissionSet.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder target, ArgumentList args, String label, CommandPermission permission) throws CommandException {
    if (ArgumentPermissions.checkModifyPerms(plugin, sender, permission, target)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    String node = args.get(0);
    boolean value = args.getBooleanOrInsert(1, true);
    MutableContextSet context = args.getContextOrDefault(2, plugin);

    if (ArgumentPermissions.checkContext(plugin, sender, permission, context) ||
            ArgumentPermissions.checkGroup(plugin, sender, target, context) ||
            ArgumentPermissions.checkArguments(plugin, sender, permission, node)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    Node builtNode = NodeBuilders.determineMostApplicable(node).value(value).withContext(context).build();

    if (builtNode instanceof InheritanceNode) {
        if (ArgumentPermissions.checkGroup(plugin, sender, ((InheritanceNode) builtNode).getGroupName(), context)) {
            Message.COMMAND_NO_PERMISSION.send(sender);
            return CommandResult.NO_PERMISSION;
        }
    }

    DataMutateResult result = target.setNode(DataType.NORMAL, builtNode, true);

    if (result.wasSuccessful()) {
        Message.SETPERMISSION_SUCCESS.send(sender, node, value, target.getFormattedDisplayName(), MessageUtils.contextSetToString(plugin.getLocaleManager(), context));

        LoggedAction.build().source(sender).target(target)
                .description("permission", "set", node, value, context)
                .build().submit(plugin, sender);

        StorageAssistant.save(target, sender, plugin);
        return CommandResult.SUCCESS;
    } else {
        Message.ALREADY_HASPERMISSION.send(sender, target.getFormattedDisplayName(), node, MessageUtils.contextSetToString(plugin.getLocaleManager(), context));
        return CommandResult.STATE_ERROR;
    }
}
 
Example #30
Source File: PermissionSetTemp.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, PermissionHolder target, ArgumentList args, String label, CommandPermission permission) throws CommandException {
    if (ArgumentPermissions.checkModifyPerms(plugin, sender, permission, target)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    String node = args.get(0);
    boolean value = args.getBooleanOrInsert(1, true);
    Duration duration = args.getDuration(2);
    TemporaryNodeMergeStrategy modifier = args.getTemporaryModifierAndRemove(3).orElseGet(() -> plugin.getConfiguration().get(ConfigKeys.TEMPORARY_ADD_BEHAVIOUR));
    MutableContextSet context = args.getContextOrDefault(3, plugin);

    if (ArgumentPermissions.checkContext(plugin, sender, permission, context) ||
            ArgumentPermissions.checkGroup(plugin, sender, target, context) ||
            ArgumentPermissions.checkArguments(plugin, sender, permission, node)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    Node builtNode = NodeBuilders.determineMostApplicable(node).value(value).withContext(context).expiry(duration).build();

    if (builtNode instanceof InheritanceNode) {
        if (ArgumentPermissions.checkGroup(plugin, sender, ((InheritanceNode) builtNode).getGroupName(), context)) {
            Message.COMMAND_NO_PERMISSION.send(sender);
            return CommandResult.NO_PERMISSION;
        }
    }

    DataMutateResult.WithMergedNode result = target.setNode(DataType.NORMAL, builtNode, modifier);

    if (result.getResult().wasSuccessful()) {
        duration = result.getMergedNode().getExpiryDuration();
        Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, value, target.getFormattedDisplayName(), DurationFormatter.LONG.format(duration), MessageUtils.contextSetToString(plugin.getLocaleManager(), context));

        LoggedAction.build().source(sender).target(target)
                .description("permission", "settemp", node, value, duration, context)
                .build().submit(plugin, sender);

        StorageAssistant.save(target, sender, plugin);
        return CommandResult.SUCCESS;
    } else {
        Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, target.getFormattedDisplayName(), node, MessageUtils.contextSetToString(plugin.getLocaleManager(), context));
        return CommandResult.STATE_ERROR;
    }
}