Search in sources :

Example 6 with Dynamic

use of alexh.weak.Dynamic in project DiscordSRV by Scarsz.

the class AlertListener method runAlertsForEvent.

private void runAlertsForEvent(Object event) {
    boolean command = event instanceof PlayerCommandPreprocessEvent || event instanceof ServerCommandEvent;
    boolean active = false;
    String eventName = getEventName(event);
    for (String trigger : activeTriggers) {
        if (command && trigger.startsWith("/")) {
            active = true;
            break;
        } else if (trigger.equals(eventName.toLowerCase())) {
            active = true;
            break;
        }
    }
    if (!active) {
        // remove us from HandlerLists that we don't need (we can do this here, since we have the full class name)
        if (event instanceof Event)
            ((Event) event).getHandlers().unregister(this);
        return;
    }
    for (int i = 0; i < alerts.size(); i++) {
        Dynamic alert = alerts.get(i);
        Set<String> triggers = getTriggers(alert);
        boolean async = true;
        Dynamic asyncDynamic = alert.get("Async");
        if (asyncDynamic.isPresent()) {
            if (asyncDynamic.convert().intoString().equalsIgnoreCase("false") || asyncDynamic.convert().intoString().equalsIgnoreCase("no")) {
                async = false;
            }
        }
        outer: for (String syncName : SYNC_EVENT_NAMES) {
            for (String trigger : triggers) {
                if (trigger.equalsIgnoreCase(syncName)) {
                    async = false;
                    break outer;
                }
            }
        }
        if (async) {
            int alertIndex = i;
            Bukkit.getScheduler().runTaskAsynchronously(DiscordSRV.getPlugin(), () -> process(event, alert, triggers, alertIndex));
        } else {
            process(event, alert, triggers, i);
        }
    }
}
Also used : PlayerCommandPreprocessEvent(org.bukkit.event.player.PlayerCommandPreprocessEvent) Dynamic(alexh.weak.Dynamic) ServerCommandEvent(org.bukkit.event.server.ServerCommandEvent) PlayerCommandPreprocessEvent(org.bukkit.event.player.PlayerCommandPreprocessEvent) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) PlayerEvent(org.bukkit.event.player.PlayerEvent) ServerCommandEvent(org.bukkit.event.server.ServerCommandEvent)

Example 7 with Dynamic

use of alexh.weak.Dynamic in project DiscordSRV by Scarsz.

the class PresenceUpdater method run.

@Override
public void run() {
    while (true) {
        int rate = DiscordSRV.config().getInt("StatusUpdateRateInMinutes");
        if (rate < 1)
            rate = 1;
        if (DiscordUtil.getJda() != null) {
            Dynamic dynamic = DiscordSRV.config().dget("DiscordGameStatus");
            List<String> statuses = new LinkedList<>();
            if (dynamic.isList()) {
                statuses.addAll(dynamic.asList());
            } else {
                statuses.add(dynamic.convert().intoString());
            }
            String status;
            if (statuses.size() == 0) {
                status = null;
            } else {
                int nextStatusIndex = lastStatusIndex + 1;
                if (nextStatusIndex >= statuses.size())
                    nextStatusIndex = 0;
                status = statuses.size() >= nextStatusIndex + 1 ? statuses.get(nextStatusIndex) : null;
                lastStatusIndex = nextStatusIndex;
            }
            if (status != null) {
                status = status.replace("%online%", String.valueOf(PlayerUtil.getOnlinePlayers(true).size()));
                status = PlaceholderUtil.replacePlaceholders(status);
                // remove color codes
                status = MessageUtil.strip(status);
            }
            boolean same = Objects.equals(lastStatus, status);
            lastStatus = status;
            if (!same) {
                if (StringUtils.isNotBlank(status)) {
                    DiscordSRV.debug(Debug.PRESENCE, "Setting presence to \"" + status + "\"");
                    if (StringUtils.startsWithIgnoreCase(status, "watching")) {
                        String removed = status.substring("watching".length()).trim();
                        DiscordUtil.getJda().getPresence().setPresence(Activity.watching(removed), false);
                    } else if (StringUtils.startsWithIgnoreCase(status, "listening to")) {
                        String removed = status.substring("listening to".length()).trim();
                        DiscordUtil.getJda().getPresence().setPresence(Activity.listening(removed), false);
                    } else if (StringUtils.startsWithIgnoreCase(status, "playing")) {
                        String removed = status.substring("playing".length()).trim();
                        DiscordUtil.getJda().getPresence().setPresence(Activity.playing(removed), false);
                    } else {
                        DiscordUtil.getJda().getPresence().setPresence(Activity.playing(status), false);
                    }
                } else {
                    DiscordUtil.getJda().getPresence().setPresence((Activity) null, false);
                    DiscordSRV.debug(Debug.PRESENCE, "Cleared presence status");
                }
            }
        } else {
            DiscordSRV.debug(Debug.PRESENCE, "Skipping presence status update cycle, JDA was null");
        }
        try {
            Thread.sleep(TimeUnit.MINUTES.toMillis(rate));
        } catch (InterruptedException ignored) {
            DiscordSRV.debug(Debug.PRESENCE, "Broke from Status Updater thread: sleep interrupted");
            return;
        }
    }
}
Also used : Dynamic(alexh.weak.Dynamic) LinkedList(java.util.LinkedList)

Example 8 with Dynamic

use of alexh.weak.Dynamic in project DiscordSRV by Scarsz.

the class RequireLinkModule method check.

private void check(String eventType, EventPriority priority, String playerName, UUID playerUuid, String ip, BiConsumer<String, String> disallow) {
    if (!isEnabled())
        return;
    if (!eventType.equals(DiscordSRV.config().getString("Require linked account to play.Listener event")))
        return;
    String requestedPriority = DiscordSRV.config().getString("Require linked account to play.Listener priority");
    EventPriority targetPriority = Arrays.stream(EventPriority.values()).filter(p -> p.name().equalsIgnoreCase(requestedPriority)).findFirst().orElse(EventPriority.LOWEST);
    if (priority != targetPriority)
        return;
    try {
        if (getBypassNames().contains(playerName)) {
            DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " is on the bypass list, bypassing linking checks");
            return;
        }
        if (checkWhitelist()) {
            boolean whitelisted = Bukkit.getServer().getWhitelistedPlayers().stream().map(OfflinePlayer::getUniqueId).anyMatch(u -> u.equals(playerUuid));
            if (whitelisted) {
                DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " is bypassing link requirement, player is whitelisted");
                return;
            }
        }
        boolean onlyCheckBannedPlayers = onlyCheckBannedPlayers();
        if (!checkBannedPlayers() || onlyCheckBannedPlayers) {
            boolean banned = false;
            if (Bukkit.getServer().getBannedPlayers().stream().anyMatch(p -> p.getUniqueId().equals(playerUuid))) {
                if (!onlyCheckBannedPlayers) {
                    DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " is banned, skipping linked check");
                    return;
                }
                banned = true;
            }
            if (!banned && Bukkit.getServer().getIPBans().stream().anyMatch(ip::equals)) {
                if (!onlyCheckBannedPlayers) {
                    DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " connecting with banned IP " + ip + ", skipping linked check");
                    return;
                }
                banned = true;
            }
            if (onlyCheckBannedPlayers && !banned) {
                DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " is bypassing link requirement because \"Only check banned players\" is enabled");
                return;
            }
        }
        if (!DiscordSRV.isReady) {
            DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " connecting before DiscordSRV is ready, denying login");
            disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_OTHER.name(), MessageUtil.translateLegacy(getDiscordSRVStillStartingKickMessage()));
            return;
        }
        String discordId = DiscordSRV.getPlugin().getAccountLinkManager().getDiscordIdBypassCache(playerUuid);
        if (discordId == null) {
            Member botMember = DiscordSRV.getPlugin().getMainGuild().getSelfMember();
            String botName = botMember.getEffectiveName() + "#" + botMember.getUser().getDiscriminator();
            String code = DiscordSRV.getPlugin().getAccountLinkManager().generateCode(playerUuid);
            String inviteLink = DiscordSRV.config().getString("DiscordInviteLink");
            DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " is NOT linked to a Discord account, denying login");
            disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST.name(), MessageUtil.translateLegacy(DiscordSRV.config().getString("Require linked account to play.Not linked message")).replace("{BOT}", botName).replace("{CODE}", code).replace("{INVITE}", inviteLink));
            return;
        }
        Dynamic mustBeInDiscordServerOption = DiscordSRV.config().dget("Require linked account to play.Must be in Discord server");
        if (mustBeInDiscordServerOption.is(Boolean.class)) {
            boolean mustBePresent = mustBeInDiscordServerOption.as(Boolean.class);
            boolean isPresent = DiscordUtil.getJda().retrieveUserById(discordId).complete().getMutualGuilds().contains(DiscordSRV.getPlugin().getMainGuild());
            if (mustBePresent && !isPresent) {
                DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + "'s linked Discord account is NOT present, denying login");
                disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST.name(), MessageUtil.translateLegacy(DiscordSRV.config().getString("Require linked account to play.Messages.Not in server")).replace("{INVITE}", DiscordSRV.config().getString("DiscordInviteLink")));
                return;
            }
        } else {
            Set<String> targets = new HashSet<>();
            if (mustBeInDiscordServerOption.isList()) {
                mustBeInDiscordServerOption.children().forEach(dynamic -> targets.add(dynamic.toString()));
            } else {
                targets.add(mustBeInDiscordServerOption.convert().intoString());
            }
            for (String guildId : targets) {
                try {
                    Guild guild = DiscordUtil.getJda().getGuildById(guildId);
                    if (guild != null) {
                        boolean inServer = guild.retrieveMemberById(discordId).complete() != null;
                        if (!inServer) {
                            DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + "'s linked Discord account is NOT present, denying login");
                            disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST.name(), MessageUtil.translateLegacy(DiscordSRV.config().getString("Require linked account to play.Messages.Not in server")).replace("{INVITE}", DiscordSRV.config().getString("DiscordInviteLink")));
                            return;
                        }
                    } else {
                        DiscordSRV.debug(Debug.REQUIRE_LINK, "Failed to get Discord server by ID " + guildId + ": bot is not in server");
                    }
                } catch (NumberFormatException e) {
                    DiscordSRV.debug(Debug.REQUIRE_LINK, "Failed to get Discord server by ID " + guildId + ": not a parsable long");
                }
            }
        }
        List<String> subRoleIds = DiscordSRV.config().getStringList("Require linked account to play.Subscriber role.Subscriber roles");
        if (isSubRoleRequired() && !subRoleIds.isEmpty()) {
            int failedRoleIds = 0;
            int matches = 0;
            for (String subRoleId : subRoleIds) {
                if (StringUtils.isBlank(subRoleId)) {
                    failedRoleIds++;
                    continue;
                }
                Role role = null;
                try {
                    role = DiscordUtil.getJda().getRoleById(subRoleId);
                } catch (Throwable ignored) {
                }
                if (role == null) {
                    failedRoleIds++;
                    continue;
                }
                Member member = role.getGuild().getMemberById(discordId);
                if (member != null && member.getRoles().contains(role)) {
                    matches++;
                }
            }
            if (failedRoleIds == subRoleIds.size()) {
                DiscordSRV.error("Tried to authenticate " + playerName + " but no valid subscriber role IDs are found and thats a requirement; login will be denied until this is fixed.");
                disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_OTHER.name(), MessageUtil.translateLegacy(getFailedToFindRoleKickMessage()));
                return;
            }
            if (getAllSubRolesRequired() ? matches < subRoleIds.size() : matches == 0) {
                DiscordSRV.debug(Debug.REQUIRE_LINK, "Player " + playerName + " does NOT match subscriber role requirements, denying login");
                disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST.name(), MessageUtil.translateLegacy(getSubscriberRoleKickMessage()));
            }
        }
    } catch (Exception exception) {
        DiscordSRV.error("Failed to check player: " + playerName, exception);
        disallow.accept(AsyncPlayerPreLoginEvent.Result.KICK_OTHER.name(), MessageUtil.translateLegacy(getUnknownFailureKickMessage()));
    }
}
Also used : Dynamic(alexh.weak.Dynamic) Guild(net.dv8tion.jda.api.entities.Guild) Role(net.dv8tion.jda.api.entities.Role) Member(net.dv8tion.jda.api.entities.Member) EventPriority(org.bukkit.event.EventPriority)

Aggregations

Dynamic (alexh.weak.Dynamic)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Matcher (java.util.regex.Matcher)2 GenericEvent (net.dv8tion.jda.api.events.GenericEvent)2 StringUtils (org.apache.commons.lang3.StringUtils)2 PlayerCommandPreprocessEvent (org.bukkit.event.player.PlayerCommandPreprocessEvent)2 PlayerEvent (org.bukkit.event.player.PlayerEvent)2 Weak (alexh.weak.Weak)1 Language (github.scarsz.configuralize.Language)1 Debug (github.scarsz.discordsrv.Debug)1 DiscordSRV (github.scarsz.discordsrv.DiscordSRV)1 Subscribe (github.scarsz.discordsrv.api.Subscribe)1 ExpiringDualHashBidiMap (github.scarsz.discordsrv.objects.ExpiringDualHashBidiMap)1 Lag (github.scarsz.discordsrv.objects.Lag)1 MessageFormat (github.scarsz.discordsrv.objects.MessageFormat)1 github.scarsz.discordsrv.util (github.scarsz.discordsrv.util)1 File (java.io.File)1 IOException (java.io.IOException)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1