Search in sources :

Example 6 with Subject

use of org.spongepowered.api.service.permission.Subject in project UltimateChat by FabioZumbi12.

the class UCMessages method formatTags.

public static String formatTags(String tag, String text, Object cmdSender, Object receiver, String msg, UCChannel ch) {
    if (receiver instanceof CommandSource && tag.equals("message")) {
        text = text.replace("{message}", mention(cmdSender, receiver, msg));
        if (UChat.get().getConfig().root().general.item_hand.enable) {
            text = text.replace(UChat.get().getConfig().root().general.item_hand.placeholder, formatTags("", UCUtil.toColor(UChat.get().getConfig().root().general.item_hand.format), cmdSender, receiver, msg, ch));
        }
    } else {
        text = text.replace("{message}", msg);
    }
    if (tag.equals("message") && !UChat.get().getConfig().root().general.enable_tags_on_messages) {
        return text;
    }
    text = text.replace("{ch-color}", ch.getColor()).replace("{ch-name}", ch.getName()).replace("{ch-alias}", ch.getAlias());
    if (UChat.get().getConfig().root().jedis.enable && ch.useJedis()) {
        text = text.replace("{jedis-id}", UChat.get().getConfig().root().jedis.server_id);
    }
    if (cmdSender instanceof CommandSource) {
        text = text.replace("{playername}", ((CommandSource) cmdSender).getName());
        if (receiver instanceof CommandSource) {
            text = text.replace("{receivername}", ((CommandSource) receiver).getName());
        }
        if (receiver instanceof String) {
            text = text.replace("{receivername}", receiver.toString());
        }
    } else {
        text = text.replace("{playername}", (String) cmdSender);
        if (receiver instanceof CommandSource)
            text = text.replace("{receivername}", ((CommandSource) receiver).getName());
        if (receiver instanceof String)
            text = text.replace("{receivername}", (String) receiver);
    }
    for (String repl : registeredReplacers.keySet()) {
        if (registeredReplacers.get(repl).equals(repl)) {
            text = text.replace(repl, "");
            continue;
        }
        text = text.replace(repl, registeredReplacers.get(repl));
    }
    if (defFormat.length > 0) {
        StringBuilder all = new StringBuilder();
        for (int i = 0; i < defFormat.length; i++) {
            if (i == 0)
                text = text.replace("{chat_header}", defFormat[i]);
            if (i == 1)
                text = text.replace("{chat_body}", defFormat[i]);
            if (i == 2)
                text = text.replace("{chat_footer}", defFormat[i]);
            all.append(defFormat[i]);
        }
        text = text.replace("{chat_all}", all.toString());
    }
    if (text.contains("{time-now}")) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        text = text.replace("{time-now}", sdf.format(cal.getTime()));
    }
    if (cmdSender instanceof Player) {
        Player sender = (Player) cmdSender;
        if (text.contains("{nickname}") && sender.get(Keys.DISPLAY_NAME).isPresent()) {
            String nick = sender.get(Keys.DISPLAY_NAME).get().toPlain();
            if (!nick.equals(sender.getName())) {
                text = text.replace("{nickname}", nick);
                text = text.replace("{nick-symbol}", UChat.get().getConfig().root().general.nick_symbol);
            } else if (Sponge.getPluginManager().getPlugin("nucleus").isPresent() && NucleusAPI.getNicknameService().isPresent()) {
                Optional<Text> opNick = NucleusAPI.getNicknameService().get().getNickname(sender);
                if (opNick.isPresent()) {
                    nick = TextSerializers.FORMATTING_CODE.serialize(opNick.get());
                    text = text.replace("{nick-symbol}", UChat.get().getConfig().root().general.nick_symbol);
                }
            }
            text = text.replace("{nickname}", nick);
        }
        // replace item hand
        text = text.replace(UChat.get().getConfig().root().general.item_hand.placeholder, UCUtil.toColor(UChat.get().getConfig().root().general.item_hand.format));
        ItemStack item = null;
        if (sender.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
            item = sender.getItemInHand(HandTypes.MAIN_HAND).get();
        } else if (sender.getItemInHand(HandTypes.OFF_HAND).isPresent()) {
            item = sender.getItemInHand(HandTypes.OFF_HAND).get();
        }
        if (text.contains("{hand-") && item != null) {
            text = text.replace("{hand-durability}", item.get(Keys.ITEM_DURABILITY).isPresent() ? String.valueOf(item.get(Keys.ITEM_DURABILITY).get()) : "").replace("{hand-name}", item.getItem().getTranslation().get());
            if (item.get(Keys.ITEM_LORE).isPresent()) {
                StringBuilder lorestr = new StringBuilder();
                for (Text line : item.get(Keys.ITEM_LORE).get()) {
                    lorestr.append("\n ").append(line.toPlain());
                }
                if (lorestr.length() >= 2) {
                    text = text.replace("{hand-lore}", lorestr.toString().substring(0, lorestr.length() - 1));
                }
            }
            if (item.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
                StringBuilder str = new StringBuilder();
                str.append(UChat.get().getVHelper().getEnchantments(str, item));
                if (str.length() >= 2) {
                    text = text.replace("{hand-enchants}", str.toString().substring(0, str.length() - 1));
                }
            }
            text = text.replace("{hand-amount}", String.valueOf(item.getQuantity()));
            text = text.replace("{hand-name}", item.getItem().getName());
            text = text.replace("{hand-type}", item.getItem().getTranslation().get());
        } else {
            text = text.replace("{hand-name}", UChat.get().getLang().get("chat.emptyslot"));
            text = text.replace("{hand-type}", "Air");
        }
        if (text.contains("{world}")) {
            String world = sender.getWorld().getName();
            text = text.replace("{world}", UChat.get().getConfig().root().general.world_names.getOrDefault(world, world));
        }
        if (text.contains("{balance}") && UChat.get().getEco() != null) {
            UniqueAccount acc = UChat.get().getEco().getOrCreateAccount(sender.getUniqueId()).get();
            text = text.replace("{balance}", "" + acc.getBalance(UChat.get().getEco().getDefaultCurrency()).intValue());
        }
        // parse permissions options
        try {
            // player options
            Pattern pp = Pattern.compile("\\{player_option_(.+?)\\}");
            Matcher pm = pp.matcher(text);
            while (pm.find()) {
                if (sender.getOption(pm.group(1)).isPresent() && !text.contains(sender.getOption(pm.group(1)).get())) {
                    text = text.replace("{player_option_" + pm.group(1) + "}", sender.getOption(pm.group(1)).get());
                    pm = pp.matcher(text);
                }
            }
            // group options
            Subject sub = UChat.get().getPerms().getGroupAndTag(sender);
            if (sub != null) {
                text = text.replace("{option_group}", UChat.get().getConfig().root().general.group_names.getOrDefault(sub.getIdentifier(), sub.getIdentifier()));
                if (sub.getOption("display_name").isPresent()) {
                    text = text.replace("{option_display_name}", sub.getOption("display_name").get());
                } else {
                    text = text.replace("{option_display_name}", UChat.get().getConfig().root().general.group_names.getOrDefault(sub.getIdentifier(), sub.getIdentifier()));
                }
                Pattern gp = Pattern.compile("\\{option_(.+?)\\}");
                Matcher gm = gp.matcher(text);
                while (gm.find()) {
                    if (sub.getOption(gm.group(1)).isPresent() && !text.contains(sub.getOption(gm.group(1)).get())) {
                        text = text.replace("{option_" + gm.group(1) + "}", sub.getOption(gm.group(1)).get());
                        gm = gp.matcher(text);
                    }
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        if (text.contains("{clan_") && UChat.get().getConfig().root().hooks.MCClans.enable) {
            Optional<ClanService> clanServiceOpt = Sponge.getServiceManager().provide(ClanService.class);
            if (clanServiceOpt.isPresent()) {
                ClanService clan = clanServiceOpt.get();
                ClanPlayer cp = clan.getClanPlayer(sender.getUniqueId());
                if (cp != null && cp.isMemberOfAClan()) {
                    text = text.replace("{clan_name}", checkEmpty(cp.getClan().getName())).replace("{clan_tag}", cp.getClan().getTag()).replace("{clan_tag_color}", TextSerializers.FORMATTING_CODE.serialize(cp.getClan().getTagColored())).replace("{clan_kdr}", "" + cp.getClan().getKDR()).replace("{clan_player_rank}", checkEmpty(cp.getRank().getName())).replace("{clan_player_kdr}", "" + cp.getKillDeath().getKDR()).replace("{clan_player_ffprotected}", String.valueOf(cp.isFfProtected())).replace("{clan_player_isowner}", String.valueOf(cp.getClan().getOwner().equals(cp)));
                }
            }
        }
        if (Sponge.getPluginManager().getPlugin("placeholderapi").isPresent()) {
            Optional<PlaceholderService> phapiOpt = Sponge.getServiceManager().provide(PlaceholderService.class);
            Pattern p = Pattern.compile("\\%([^\\%]*)\\%");
            if (phapiOpt.isPresent() && p.matcher(text).find()) {
                PlaceholderService phapi = phapiOpt.get();
                // fix last color from string
                String lastcolor = text.length() > 1 ? text.substring(text.length() - 2, text.length()) : "";
                if (!Pattern.compile("(&([A-Fa-fK-Ok-oRr0-9]))").matcher(lastcolor).find())
                    lastcolor = "";
                text = TextSerializers.FORMATTING_CODE.serialize(phapi.replacePlaceholders(text, sender, receiver, p)) + lastcolor;
            }
        }
    }
    text = text.replace("{option_suffix}", "&r: ");
    if (cmdSender instanceof CommandSource) {
        text = text.replace("{nickname}", UChat.get().getConfig().root().general.console_tag.replace("{console}", ((CommandSource) cmdSender).getName()));
    } else {
        text = text.replace("{nickname}", UChat.get().getConfig().root().general.console_tag.replace("{console}", (String) cmdSender));
    }
    // remove blank items
    text = text.replaceAll("\\{.*\\}", "");
    if (!tag.equals("message")) {
        for (String rpl : UChat.get().getConfig().root().general.remove_from_chat) {
            text = text.replace(UCUtil.toColor(rpl), "");
        }
    }
    if (text.equals(" ") || text.equals("  ")) {
        return text = "";
    }
    return text;
}
Also used : Pattern(java.util.regex.Pattern) Player(org.spongepowered.api.entity.living.player.Player) ClanPlayer(nl.riebie.mcclans.api.ClanPlayer) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) CommandSource(org.spongepowered.api.command.CommandSource) ClanPlayer(nl.riebie.mcclans.api.ClanPlayer) PlaceholderService(me.rojo8399.placeholderapi.PlaceholderService) Subject(org.spongepowered.api.service.permission.Subject) ItemStack(org.spongepowered.api.item.inventory.ItemStack) ExecutionException(java.util.concurrent.ExecutionException) SimpleDateFormat(java.text.SimpleDateFormat) ClanService(nl.riebie.mcclans.api.ClanService)

Example 7 with Subject

use of org.spongepowered.api.service.permission.Subject in project Nucleus by NucleusPowered.

the class SetupPermissionsCommand method setupGroups.

private void setupGroups(CommandSource src) throws Exception {
    String ownerGroup = "owner";
    String adminGroup = "admin";
    String modGroup = "mod";
    String defaultGroup = "default";
    MessageProvider messageProvider = Nucleus.getNucleus().getMessageProvider();
    // Create groups
    PermissionService permissionService = Sponge.getServiceManager().provide(PermissionService.class).orElseThrow(() -> ReturnMessageException.fromKey("args.permissiongroup.noservice"));
    // check for admin
    Subject owner = getSubject(ownerGroup, src, permissionService, messageProvider);
    Subject admin = getSubject(adminGroup, src, permissionService, messageProvider);
    Subject mod = getSubject(modGroup, src, permissionService, messageProvider);
    Subject defaults = getSubject(defaultGroup, src, permissionService, messageProvider);
    src.sendMessage(messageProvider.getTextMessageWithFormat("command.nucleus.permission.inherit", adminGroup, ownerGroup));
    owner.getSubjectData().addParent(ImmutableSet.of(), admin.asSubjectReference());
    src.sendMessage(messageProvider.getTextMessageWithFormat("command.nucleus.permission.inherit", modGroup, adminGroup));
    admin.getSubjectData().addParent(ImmutableSet.of(), mod.asSubjectReference());
    src.sendMessage(messageProvider.getTextMessageWithFormat("command.nucleus.permission.inherit", defaultGroup, modGroup));
    mod.getSubjectData().addParent(ImmutableSet.of(), defaults.asSubjectReference());
    src.sendMessage(messageProvider.getTextMessageWithFormat("command.nucleus.permission.perms"));
    setupPerms(src, owner, SuggestedLevel.OWNER, false, false);
    setupPerms(src, admin, SuggestedLevel.ADMIN, false, false);
    setupPerms(src, mod, SuggestedLevel.MOD, false, false);
    setupPerms(src, defaults, SuggestedLevel.USER, false, false);
    src.sendMessage(messageProvider.getTextMessageWithFormat("command.nucleus.permission.completegroups"));
}
Also used : PermissionService(org.spongepowered.api.service.permission.PermissionService) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) Subject(org.spongepowered.api.service.permission.Subject)

Example 8 with Subject

use of org.spongepowered.api.service.permission.Subject in project Nucleus by NucleusPowered.

the class SetupPermissionsCommand method setupPerms.

private void setupPerms(CommandSource src, Subject group, SuggestedLevel level, boolean reset, boolean inherit) throws Exception {
    if (inherit && level.getLowerLevel() != null) {
        setupPerms(src, group, level.getLowerLevel(), reset, inherit);
    }
    Set<Context> globalContext = Sets.newHashSet();
    SubjectData data = group.getSubjectData();
    Set<String> definedPermissions = data.getPermissions(ImmutableSet.of()).keySet();
    Logger logger = Nucleus.getNucleus().getLogger();
    MessageProvider messageProvider = Nucleus.getNucleus().getMessageProvider();
    // Register all the permissions, but only those that have yet to be assigned.
    permissionRegistry.getPermissions().entrySet().stream().filter(x -> x.getValue().level == level).filter(x -> reset || !definedPermissions.contains(x.getKey())).forEach(x -> {
        logger.info(messageProvider.getMessageWithFormat("command.nucleus.permission.added", x.getKey(), group.getIdentifier()));
        data.setPermission(globalContext, x.getKey(), Tristate.TRUE);
    });
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.nucleus.permission.complete", level.toString().toLowerCase(), group.getIdentifier()));
}
Also used : CommandContext(org.spongepowered.api.command.args.CommandContext) Context(org.spongepowered.api.service.context.Context) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) GenericArguments(org.spongepowered.api.command.args.GenericArguments) PermissionService(org.spongepowered.api.service.permission.PermissionService) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) PermissionRegistry(io.github.nucleuspowered.nucleus.internal.PermissionRegistry) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) ServiceChangeListener(io.github.nucleuspowered.nucleus.internal.permissions.ServiceChangeListener) Subject(org.spongepowered.api.service.permission.Subject) Nullable(javax.annotation.Nullable) NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) SubjectData(org.spongepowered.api.service.permission.SubjectData) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) CommandSource(org.spongepowered.api.command.CommandSource) Context(org.spongepowered.api.service.context.Context) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Tristate(org.spongepowered.api.util.Tristate) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) Optional(java.util.Optional) Collections(java.util.Collections) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) SubjectData(org.spongepowered.api.service.permission.SubjectData) Logger(org.slf4j.Logger)

Example 9 with Subject

use of org.spongepowered.api.service.permission.Subject in project Nucleus by NucleusPowered.

the class SetupPermissionsCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    if (args.hasAny(this.withGroupsKey)) {
        if (ServiceChangeListener.isOpOnly()) {
            // Fail
            throw ReturnMessageException.fromKey("args.permissiongroup.noservice");
        }
        if (args.hasAny(this.acceptGroupKey)) {
            setupGroups(src);
        } else {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.nucleus.permission.groups.info"));
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.nucleus.permission.groups.info2").toBuilder().onClick(TextActions.runCommand("/nucleus:nucleus setupperms -g -y")).onHover(TextActions.showText(Text.of("/nucleus:nucleus setupperms -g -y"))).build());
        }
        return CommandResult.success();
    }
    // The GroupArgument should have already checked for this.
    SuggestedLevel sl = args.<SuggestedLevel>getOne(roleKey).get();
    Subject group = args.<Subject>getOne(groupKey).get();
    boolean reset = args.hasAny("r");
    boolean inherit = args.hasAny("i");
    setupPerms(src, group, sl, reset, inherit);
    return CommandResult.success();
}
Also used : SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Subject(org.spongepowered.api.service.permission.Subject)

Example 10 with Subject

use of org.spongepowered.api.service.permission.Subject in project Nucleus by NucleusPowered.

the class StandardModule method registerServices.

@SuppressWarnings("unchecked")
private void registerServices() throws Exception {
    RegisterService[] annotations = getClass().getAnnotationsByType(RegisterService.class);
    if (annotations != null && annotations.length > 0) {
        // for each annotation, attempt to register the service.
        for (RegisterService service : annotations) {
            Class<?> impl = service.value();
            // create the impl
            Object serviceImpl;
            try {
                serviceImpl = impl.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                String error = "ERROR: Cannot instantiate " + impl.getName();
                Nucleus.getNucleus().getLogger().error(error);
                throw new IllegalStateException(error, e);
            }
            Class<?> api = service.apiService();
            if (api != Object.class) {
                if (api.isInstance(serviceImpl)) {
                    // OK
                    register((Class) api, (Class) impl, serviceImpl);
                } else {
                    String error = "ERROR: " + api.getName() + " does not inherit from " + impl.getName();
                    Nucleus.getNucleus().getLogger().error(error);
                    throw new IllegalStateException(error);
                }
            } else {
                register((Class) impl, serviceImpl);
            }
            if (serviceImpl instanceof Reloadable) {
                Reloadable reloadable = (Reloadable) serviceImpl;
                Nucleus.getNucleus().registerReloadable(reloadable);
                reloadable.onReload();
            }
            if (serviceImpl instanceof ContextCalculator) {
                try {
                    // boolean matches(Context context, T calculable);
                    serviceImpl.getClass().getMethod("matches", Context.class, Subject.class);
                    // register it
                    ServiceChangeListener.getInstance().registerCalculator((ContextCalculator<Subject>) serviceImpl);
                } catch (NoSuchMethodException e) {
                // ignored
                }
            }
        }
    }
}
Also used : Subject(org.spongepowered.api.service.permission.Subject) RegisterService(io.github.nucleuspowered.nucleus.internal.annotations.RegisterService) ContextCalculator(org.spongepowered.api.service.context.ContextCalculator) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable)

Aggregations

Subject (org.spongepowered.api.service.permission.Subject)28 SubjectReference (org.spongepowered.api.service.permission.SubjectReference)11 Test (org.junit.Test)10 List (java.util.List)9 Player (org.spongepowered.api.entity.living.player.Player)9 Context (org.spongepowered.api.service.context.Context)6 Optional (java.util.Optional)5 Collectors (java.util.stream.Collectors)5 PermissionService (org.spongepowered.api.service.permission.PermissionService)5 Text (org.spongepowered.api.text.Text)5 Lists (com.google.common.collect.Lists)4 Maps (com.google.common.collect.Maps)4 Util (io.github.nucleuspowered.nucleus.Util)4 Map (java.util.Map)4 CommandSource (org.spongepowered.api.command.CommandSource)4 SuggestedLevel (io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel)3 ListPlayerCommand (io.github.nucleuspowered.nucleus.modules.playerinfo.commands.ListPlayerCommand)3 Arrays (java.util.Arrays)3 HashMap (java.util.HashMap)3 CompletableFuture (java.util.concurrent.CompletableFuture)3