Search in sources :

Example 46 with Node

use of me.lucko.luckperms.api.Node in project LuckPerms by lucko.

the class UserInfo method execute.

@SuppressWarnings("unchecked")
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List<String> args, String label) {
    if (ArgumentPermissions.checkViewPerms(plugin, sender, getPermission().get(), user)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }
    Message status = plugin.getBootstrap().isPlayerOnline(user.getUuid()) ? Message.PLAYER_ONLINE : Message.PLAYER_OFFLINE;
    Message.USER_INFO_GENERAL.send(sender, user.getName().orElse("Unknown"), user.getUuid(), user.getUuid().version() == 4 ? "&2mojang" : "&8offline", status.asString(plugin.getLocaleManager()), user.getPrimaryGroup().getValue());
    Set<Node> parents = user.getEnduringData().asSet().stream().filter(Node::isGroupNode).filter(Node::isPermanent).collect(Collectors.toSet());
    Set<Node> tempParents = user.getEnduringData().asSet().stream().filter(Node::isGroupNode).filter(Node::isTemporary).collect(Collectors.toSet());
    if (!parents.isEmpty()) {
        Message.INFO_PARENT_HEADER.send(sender);
        for (Node node : parents) {
            Message.EMPTY.send(sender, "&f-    &3> &f" + node.getGroupName() + MessageUtils.getAppendableNodeContextString(node));
        }
    }
    if (!tempParents.isEmpty()) {
        Message.INFO_TEMP_PARENT_HEADER.send(sender);
        for (Node node : tempParents) {
            Message.EMPTY.send(sender, "&f-    &3> &f" + node.getGroupName() + MessageUtils.getAppendableNodeContextString(node));
            Message.EMPTY.send(sender, "&f-    &2-    expires in " + DateUtil.formatDateDiff(node.getExpiryUnixTime()));
        }
    }
    String context = "&bNone";
    String prefix = "&bNone";
    String suffix = "&bNone";
    String meta = "&bNone";
    Contexts contexts = plugin.getContextForUser(user).orElse(null);
    if (contexts != null) {
        ContextSet contextSet = contexts.getContexts();
        if (!contextSet.isEmpty()) {
            context = contextSet.toSet().stream().map(e -> MessageUtils.contextToString(e.getKey(), e.getValue())).collect(Collectors.joining(" "));
        }
        MetaData data = user.getCachedData().getMetaData(contexts);
        if (data.getPrefix() != null) {
            prefix = "&f\"" + data.getPrefix() + "&f\"";
        }
        if (data.getSuffix() != null) {
            suffix = "&f\"" + data.getSuffix() + "&f\"";
        }
        ListMultimap<String, String> metaMap = data.getMetaMultimap();
        if (!metaMap.isEmpty()) {
            meta = metaMap.entries().stream().map(e -> MessageUtils.contextToString(e.getKey(), e.getValue())).collect(Collectors.joining(" "));
        }
    }
    Message.USER_INFO_DATA.send(sender, MessageUtils.formatBoolean(contexts != null), context, prefix, suffix, meta);
    return CommandResult.SUCCESS;
}
Also used : ContextSet(me.lucko.luckperms.api.context.ContextSet) Message(me.lucko.luckperms.common.locale.message.Message) MetaData(me.lucko.luckperms.api.caching.MetaData) Node(me.lucko.luckperms.api.Node) Contexts(me.lucko.luckperms.api.Contexts)

Example 47 with Node

use of me.lucko.luckperms.api.Node in project LuckPerms by lucko.

the class MigrationGroupManager method execute.

@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) {
    ProgressLogger log = new ProgressLogger("GroupManager");
    log.addListener(plugin.getConsoleSender());
    log.addListener(sender);
    log.log("Starting.");
    if (!args.get(0).equalsIgnoreCase("true") && !args.get(0).equalsIgnoreCase("false")) {
        log.logError("Was expecting true/false, but got " + args.get(0) + " instead.");
        return CommandResult.STATE_ERROR;
    }
    final boolean migrateAsGlobal = Boolean.parseBoolean(args.get(0));
    final Function<String, String> worldMappingFunc = s -> migrateAsGlobal ? null : s;
    if (!Bukkit.getPluginManager().isPluginEnabled("GroupManager")) {
        log.logError("Plugin not loaded.");
        return CommandResult.STATE_ERROR;
    }
    List<String> worlds = Bukkit.getWorlds().stream().map(World::getName).map(String::toLowerCase).collect(Collectors.toList());
    GroupManager gm = (GroupManager) Bukkit.getPluginManager().getPlugin("GroupManager");
    // Migrate Global Groups
    log.log("Starting global group migration.");
    GlobalGroups gg = GroupManager.getGlobalGroups();
    AtomicInteger globalGroupCount = new AtomicInteger(0);
    Iterators.iterate(gg.getGroupList(), g -> {
        String groupName = MigrationUtils.standardizeName(g.getName());
        Group group = plugin.getStorage().createAndLoadGroup(groupName, CreationCause.INTERNAL).join();
        for (String node : g.getPermissionList()) {
            if (node.isEmpty())
                continue;
            group.setPermission(MigrationUtils.parseNode(node, true).build());
        }
        for (String s : g.getInherits()) {
            if (s.isEmpty())
                continue;
            group.setPermission(NodeFactory.make(NodeFactory.groupNode(MigrationUtils.standardizeName(s))));
        }
        plugin.getStorage().saveGroup(group);
        log.logAllProgress("Migrated {} groups so far.", globalGroupCount.incrementAndGet());
    });
    log.log("Migrated " + globalGroupCount.get() + " global groups");
    // Collect data
    Map<UUID, Set<Node>> users = new HashMap<>();
    Map<UUID, String> primaryGroups = new HashMap<>();
    Map<String, Set<Node>> groups = new HashMap<>();
    WorldsHolder wh = gm.getWorldsHolder();
    // Collect data for all users and groups.
    log.log("Collecting user and group data.");
    Iterators.iterate(worlds, String::toLowerCase, world -> {
        log.log("Querying world " + world);
        WorldDataHolder wdh = wh.getWorldData(world);
        AtomicInteger groupWorldCount = new AtomicInteger(0);
        Iterators.iterate(wdh.getGroupList(), group -> {
            String groupName = MigrationUtils.standardizeName(group.getName());
            groups.putIfAbsent(groupName, new HashSet<>());
            for (String node : group.getPermissionList()) {
                if (node.isEmpty())
                    continue;
                groups.get(groupName).add(MigrationUtils.parseNode(node, true).setWorld(worldMappingFunc.apply(world)).build());
            }
            for (String s : group.getInherits()) {
                if (s.isEmpty())
                    continue;
                groups.get(groupName).add(NodeFactory.make(NodeFactory.groupNode(MigrationUtils.standardizeName(s)), true, null, worldMappingFunc.apply(world)));
            }
            String[] metaKeys = group.getVariables().getVarKeyList();
            for (String key : metaKeys) {
                String value = group.getVariables().getVarString(key);
                key = key.toLowerCase();
                if (key.isEmpty() || value.isEmpty())
                    continue;
                if (key.equals("build"))
                    continue;
                if (key.equals(NodeFactory.PREFIX_KEY) || key.equals(NodeFactory.SUFFIX_KEY)) {
                    ChatMetaType type = ChatMetaType.valueOf(key.toUpperCase());
                    groups.get(groupName).add(NodeFactory.buildChatMetaNode(type, 50, value).setWorld(worldMappingFunc.apply(world)).build());
                } else {
                    groups.get(groupName).add(NodeFactory.buildMetaNode(key, value).setWorld(worldMappingFunc.apply(world)).build());
                }
            }
            log.logAllProgress("Migrated {} groups so far in world " + world, groupWorldCount.incrementAndGet());
        });
        log.log("Migrated " + groupWorldCount.get() + " groups in world " + world);
        AtomicInteger userWorldCount = new AtomicInteger(0);
        Iterators.iterate(wdh.getUserList(), user -> {
            UUID uuid = BukkitMigrationUtils.lookupUuid(log, user.getUUID());
            if (uuid == null) {
                return;
            }
            users.putIfAbsent(uuid, new HashSet<>());
            for (String node : user.getPermissionList()) {
                if (node.isEmpty())
                    continue;
                users.get(uuid).add(MigrationUtils.parseNode(node, true).setWorld(worldMappingFunc.apply(world)).build());
            }
            // Collect sub groups
            String finalWorld = worldMappingFunc.apply(world);
            users.get(uuid).addAll(user.subGroupListStringCopy().stream().filter(n -> !n.isEmpty()).map(n -> NodeFactory.groupNode(MigrationUtils.standardizeName(n))).map(n -> NodeFactory.make(n, true, null, finalWorld)).collect(Collectors.toSet()));
            // Get primary group
            primaryGroups.put(uuid, MigrationUtils.standardizeName(user.getGroupName()));
            String[] metaKeys = user.getVariables().getVarKeyList();
            for (String key : metaKeys) {
                String value = user.getVariables().getVarString(key);
                key = key.toLowerCase();
                if (key.isEmpty() || value.isEmpty())
                    continue;
                if (key.equals("build"))
                    continue;
                if (key.equals(NodeFactory.PREFIX_KEY) || key.equals(NodeFactory.SUFFIX_KEY)) {
                    ChatMetaType type = ChatMetaType.valueOf(key.toUpperCase());
                    users.get(uuid).add(NodeFactory.buildChatMetaNode(type, 100, value).setWorld(worldMappingFunc.apply(world)).build());
                } else {
                    users.get(uuid).add(NodeFactory.buildMetaNode(key, value).setWorld(worldMappingFunc.apply(world)).build());
                }
            }
            log.logProgress("Migrated {} users so far in world " + world, userWorldCount.incrementAndGet());
        });
        log.log("Migrated " + userWorldCount.get() + " users in world " + world);
    });
    log.log("All data has now been processed, now starting the import process.");
    log.log("Found a total of " + users.size() + " users and " + groups.size() + " groups.");
    log.log("Starting group migration.");
    AtomicInteger groupCount = new AtomicInteger(0);
    Iterators.iterate(groups.entrySet(), e -> {
        Group group = plugin.getStorage().createAndLoadGroup(e.getKey(), CreationCause.INTERNAL).join();
        for (Node node : e.getValue()) {
            group.setPermission(node);
        }
        plugin.getStorage().saveGroup(group);
        log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
    });
    log.log("Migrated " + groupCount.get() + " groups");
    log.log("Starting user migration.");
    AtomicInteger userCount = new AtomicInteger(0);
    Iterators.iterate(users.entrySet(), e -> {
        User user = plugin.getStorage().loadUser(e.getKey(), null).join();
        for (Node node : e.getValue()) {
            user.setPermission(node);
        }
        String primaryGroup = primaryGroups.get(e.getKey());
        if (primaryGroup != null && !primaryGroup.isEmpty()) {
            user.setPermission(NodeFactory.buildGroupNode(primaryGroup).build());
            user.getPrimaryGroup().setStoredValue(primaryGroup);
            user.unsetPermission(NodeFactory.buildGroupNode(NodeFactory.DEFAULT_GROUP_NAME).build());
        }
        plugin.getStorage().saveUser(user);
        plugin.getUserManager().cleanup(user);
        log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
    });
    log.log("Migrated " + userCount.get() + " users.");
    log.log("Success! Migration complete.");
    return CommandResult.SUCCESS;
}
Also used : SubCommand(me.lucko.luckperms.common.command.abstraction.SubCommand) LocaleManager(me.lucko.luckperms.common.locale.LocaleManager) HashMap(java.util.HashMap) GlobalGroups(org.anjocaido.groupmanager.GlobalGroups) Function(java.util.function.Function) HashSet(java.util.HashSet) CommandSpec(me.lucko.luckperms.common.locale.command.CommandSpec) ProgressLogger(me.lucko.luckperms.common.logging.ProgressLogger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WorldsHolder(org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder) World(org.bukkit.World) Map(java.util.Map) LuckPermsPlugin(me.lucko.luckperms.common.plugin.LuckPermsPlugin) Bukkit(org.bukkit.Bukkit) CreationCause(me.lucko.luckperms.api.event.cause.CreationCause) MigrationUtils(me.lucko.luckperms.common.commands.migration.MigrationUtils) Set(java.util.Set) NodeFactory(me.lucko.luckperms.common.node.NodeFactory) Sender(me.lucko.luckperms.common.sender.Sender) UUID(java.util.UUID) Iterators(me.lucko.luckperms.common.utils.Iterators) Collectors(java.util.stream.Collectors) CommandResult(me.lucko.luckperms.common.command.CommandResult) CommandPermission(me.lucko.luckperms.common.command.access.CommandPermission) List(java.util.List) GroupManager(org.anjocaido.groupmanager.GroupManager) ChatMetaType(me.lucko.luckperms.api.ChatMetaType) Group(me.lucko.luckperms.common.model.Group) Node(me.lucko.luckperms.api.Node) User(me.lucko.luckperms.common.model.User) Predicates(me.lucko.luckperms.common.utils.Predicates) WorldDataHolder(org.anjocaido.groupmanager.dataholder.WorldDataHolder) Group(me.lucko.luckperms.common.model.Group) HashSet(java.util.HashSet) Set(java.util.Set) User(me.lucko.luckperms.common.model.User) WorldsHolder(org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder) HashMap(java.util.HashMap) Node(me.lucko.luckperms.api.Node) ChatMetaType(me.lucko.luckperms.api.ChatMetaType) ProgressLogger(me.lucko.luckperms.common.logging.ProgressLogger) World(org.bukkit.World) GroupManager(org.anjocaido.groupmanager.GroupManager) WorldDataHolder(org.anjocaido.groupmanager.dataholder.WorldDataHolder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GlobalGroups(org.anjocaido.groupmanager.GlobalGroups) UUID(java.util.UUID)

Example 48 with Node

use of me.lucko.luckperms.api.Node in project LuckPerms by lucko.

the class MigrationPowerfulPerms method applyGroup.

private void applyGroup(PermissionManager pm, PermissionHolder holder, CachedGroup g, String server) {
    Group group = pm.getGroup(g.getGroupId());
    String node = NodeFactory.groupNode(MigrationUtils.standardizeName(group.getName()));
    long expireAt = 0L;
    if (g.willExpire()) {
        expireAt = g.getExpirationDate().getTime() / 1000L;
    }
    Node.Builder nb = NodeFactory.builder(node);
    if (expireAt != 0) {
        nb.setExpiry(expireAt);
    }
    if (server != null) {
        nb.setServer(server);
    }
    holder.setPermission(nb.build());
}
Also used : CachedGroup(com.github.gustav9797.PowerfulPermsAPI.CachedGroup) Group(com.github.gustav9797.PowerfulPermsAPI.Group) Node(me.lucko.luckperms.api.Node)

Example 49 with Node

use of me.lucko.luckperms.api.Node in project LuckPerms by lucko.

the class MigrationZPermissions method execute.

@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) {
    ProgressLogger log = new ProgressLogger("zPermissions");
    log.addListener(plugin.getConsoleSender());
    log.addListener(sender);
    log.log("Starting.");
    if (!Bukkit.getPluginManager().isPluginEnabled("zPermissions")) {
        log.logError("Plugin not loaded.");
        return CommandResult.STATE_ERROR;
    }
    if (!Bukkit.getServicesManager().isProvidedFor(ZPermissionsService.class)) {
        log.logError("Plugin not loaded.");
        return CommandResult.STATE_ERROR;
    }
    ZPermissionsService service = Bukkit.getServicesManager().getRegistration(ZPermissionsService.class).getProvider();
    PermissionService internalService;
    try {
        Field psField = service.getClass().getDeclaredField("permissionService");
        psField.setAccessible(true);
        internalService = (PermissionService) psField.get(service);
    } catch (Exception e) {
        e.printStackTrace();
        return CommandResult.FAILURE;
    }
    // Migrate all groups
    log.log("Starting group migration.");
    Map<UUID, Set<Node>> userParents = new HashMap<>();
    AtomicInteger groupCount = new AtomicInteger(0);
    AtomicInteger maxWeight = new AtomicInteger(0);
    Iterators.iterate(internalService.getEntities(true), entity -> {
        String groupName = MigrationUtils.standardizeName(entity.getDisplayName());
        Group group = plugin.getStorage().createAndLoadGroup(groupName, CreationCause.INTERNAL).join();
        int weight = entity.getPriority();
        maxWeight.set(Math.max(maxWeight.get(), weight));
        migrateEntity(group, entity, weight);
        MigrationUtils.setGroupWeight(group, weight);
        // store user data for later
        Set<Membership> members = entity.getMemberships();
        for (Membership membership : members) {
            UUID uuid = BukkitMigrationUtils.lookupUuid(log, membership.getMember());
            if (uuid == null) {
                continue;
            }
            Set<Node> nodes = userParents.computeIfAbsent(uuid, u -> new HashSet<>());
            if (membership.getExpiration() == null) {
                nodes.add(NodeFactory.buildGroupNode(groupName).build());
            } else {
                long expiry = membership.getExpiration().toInstant().getEpochSecond();
                nodes.add(NodeFactory.buildGroupNode(groupName).setExpiry(expiry).build());
            }
        }
        plugin.getStorage().saveGroup(group);
        log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
    });
    log.log("Migrated " + groupCount.get() + " groups");
    // Migrate all tracks
    log.log("Starting track migration.");
    AtomicInteger trackCount = new AtomicInteger(0);
    Iterators.iterate(service.getAllTracks(), t -> {
        String trackName = MigrationUtils.standardizeName(t);
        Track track = plugin.getStorage().createAndLoadTrack(trackName, CreationCause.INTERNAL).join();
        track.setGroups(service.getTrackGroups(t));
        plugin.getStorage().saveTrack(track);
        log.logAllProgress("Migrated {} tracks so far.", trackCount.incrementAndGet());
    });
    log.log("Migrated " + trackCount.get() + " tracks");
    // Migrate all users.
    log.log("Starting user migration.");
    maxWeight.addAndGet(10);
    AtomicInteger userCount = new AtomicInteger(0);
    Set<UUID> usersToMigrate = new HashSet<>(userParents.keySet());
    usersToMigrate.addAll(service.getAllPlayersUUID());
    Iterators.iterate(usersToMigrate, u -> {
        PermissionEntity entity = internalService.getEntity(null, u, false);
        String username = null;
        if (entity != null) {
            username = entity.getDisplayName();
        }
        User user = plugin.getStorage().loadUser(u, username).join();
        // migrate permissions & meta
        if (entity != null) {
            migrateEntity(user, entity, maxWeight.get());
        }
        // migrate groups
        Set<Node> parents = userParents.get(u);
        if (parents != null) {
            parents.forEach(user::setPermission);
        }
        user.getPrimaryGroup().setStoredValue(MigrationUtils.standardizeName(service.getPlayerPrimaryGroup(u)));
        plugin.getUserManager().cleanup(user);
        plugin.getStorage().saveUser(user);
        log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
    });
    log.log("Migrated " + userCount.get() + " users.");
    log.log("Success! Migration complete.");
    return CommandResult.SUCCESS;
}
Also used : Group(me.lucko.luckperms.common.model.Group) HashSet(java.util.HashSet) Set(java.util.Set) User(me.lucko.luckperms.common.model.User) HashMap(java.util.HashMap) Node(me.lucko.luckperms.api.Node) ProgressLogger(me.lucko.luckperms.common.logging.ProgressLogger) PermissionService(org.tyrannyofheaven.bukkit.zPermissions.dao.PermissionService) Field(java.lang.reflect.Field) Membership(org.tyrannyofheaven.bukkit.zPermissions.model.Membership) UUID(java.util.UUID) PermissionEntity(org.tyrannyofheaven.bukkit.zPermissions.model.PermissionEntity) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Track(me.lucko.luckperms.common.model.Track) ZPermissionsService(org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService)

Example 50 with Node

use of me.lucko.luckperms.api.Node in project LuckPerms by lucko.

the class LPPermissionAttachment method setPermissionInternal.

private void setPermissionInternal(String name, boolean value) {
    if (!this.permissible.getPlugin().getConfiguration().get(ConfigKeys.APPLY_BUKKIT_ATTACHMENT_PERMISSIONS)) {
        return;
    }
    // construct a node for the permission being set
    // we use the servers static context to *try* to ensure that the node will apply
    Node node = NodeFactory.builder(name).setValue(value).withExtraContext(this.permissible.getPlugin().getContextManager().getStaticContext()).build();
    // convert the constructed node to a transient node instance to refer back to this attachment
    ImmutableTransientNode<LPPermissionAttachment> transientNode = ImmutableTransientNode.of(node, this);
    // set the transient node
    User user = this.permissible.getUser();
    if (user.setTransientPermission(transientNode).asBoolean()) {
        user.reloadCachedData();
    }
}
Also used : User(me.lucko.luckperms.common.model.User) ImmutableTransientNode(me.lucko.luckperms.common.node.ImmutableTransientNode) Node(me.lucko.luckperms.api.Node)

Aggregations

Node (me.lucko.luckperms.api.Node)56 LocalizedNode (me.lucko.luckperms.api.LocalizedNode)15 Group (me.lucko.luckperms.common.model.Group)15 User (me.lucko.luckperms.common.model.User)13 Map (java.util.Map)12 ImmutableLocalizedNode (me.lucko.luckperms.common.node.ImmutableLocalizedNode)12 List (java.util.List)11 NodeFactory (me.lucko.luckperms.common.node.NodeFactory)10 Message (me.lucko.luckperms.common.locale.message.Message)9 LuckPermsPlugin (me.lucko.luckperms.common.plugin.LuckPermsPlugin)9 Sender (me.lucko.luckperms.common.sender.Sender)9 Collectors (java.util.stream.Collectors)8 MutableContextSet (me.lucko.luckperms.api.context.MutableContextSet)8 CommandResult (me.lucko.luckperms.common.command.CommandResult)8 CommandPermission (me.lucko.luckperms.common.command.access.CommandPermission)8 LocaleManager (me.lucko.luckperms.common.locale.LocaleManager)8 CommandSpec (me.lucko.luckperms.common.locale.command.CommandSpec)8 Predicates (me.lucko.luckperms.common.utils.Predicates)8 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7