Search in sources :

Example 1 with MatchAction

use of com.sx4.bot.entities.mod.auto.MatchAction in project Sx4 by sx4-discord-bot.

the class AntiRegexHandler method handle.

public void handle(Message message) {
    if (!message.isFromGuild()) {
        return;
    }
    Member member = message.getMember();
    if (member == null) {
        return;
    }
    User user = member.getUser();
    if (user.isBot()) {
        return;
    }
    Guild guild = message.getGuild();
    Member selfMember = guild.getSelfMember();
    GuildMessageChannel messageChannel = message.getGuildChannel();
    long guildId = guild.getIdLong(), userId = member.getIdLong(), channelId = (messageChannel instanceof ThreadChannel ? ((ThreadChannel) messageChannel).getParentChannel() : messageChannel).getIdLong();
    Category parent = messageChannel instanceof ICategorizableChannel ? ((ICategorizableChannel) messageChannel).getParentCategory() : null;
    List<Role> roles = member.getRoles();
    String content = message.getContentRaw();
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", guild.getIdLong())));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", guild.getIdLong()), Filters.exists("enabled", false))), Aggregates.group(null, Accumulators.push("regexes", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("premium", "$premium"), Accumulators.max("regexes", "$regexes")), Aggregates.project(Projections.computed("regexes", Operators.let(new Document("regexes", Operators.ifNull("$regexes", Collections.EMPTY_LIST)), Operators.cond(Operators.ifNull("$premium", false), "$$regexes", Operators.concatArrays(Operators.filter("$$regexes", Operators.ne("$$this.type", RegexType.REGEX.getId())), Operators.slice(Operators.filter("$$regexes", Operators.eq("$$this.type", RegexType.REGEX.getId())), 0, 3)))))));
    this.bot.getMongo().aggregateRegexes(pipeline).whenComplete((documents, exception) -> {
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        this.executor.submit(() -> {
            List<CompletableFuture<Document>> matches = new ArrayList<>();
            Regexes: for (Document regex : data.getList("regexes", Document.class)) {
                if (member.hasPermission(Permission.ADMINISTRATOR) && regex.getBoolean("admin", true)) {
                    continue;
                }
                List<Document> channels = regex.getList("whitelist", Document.class, Collections.emptyList());
                Document channel = channels.stream().filter(d -> (d.getInteger("type") == WhitelistType.CHANNEL.getId() && d.getLong("id") == channelId) || (d.getInteger("type") == WhitelistType.CATEGORY.getId() && parent != null && d.getLong("id") == parent.getIdLong())).min(Comparator.comparingInt(d -> d.getInteger("type", 0))).orElse(MongoDatabase.EMPTY_DOCUMENT);
                List<Document> holders = channel.getList("holders", Document.class, Collections.emptyList());
                for (Document holder : holders) {
                    long holderId = holder.getLong("id");
                    int type = holder.getInteger("type");
                    if (type == HolderType.USER.getType() && userId == holderId) {
                        continue Regexes;
                    } else if (type == HolderType.ROLE.getType() && (guildId == holderId || roles.stream().anyMatch(role -> role.getIdLong() == holderId))) {
                        continue Regexes;
                    }
                }
                RegexType type = RegexType.fromId(regex.getInteger("type"));
                Pattern pattern = type == RegexType.REGEX ? Pattern.compile(regex.getString("pattern")) : this.invitePattern;
                Matcher matcher;
                try {
                    matcher = this.executor.submit(() -> pattern.matcher(content)).get(2000, TimeUnit.MILLISECONDS);
                } catch (TimeoutException | InterruptedException | ExecutionException e) {
                    continue;
                }
                Set<String> codes = new HashSet<>();
                int matchCount = 0, totalCount = 0;
                while (matcher.find()) {
                    List<Document> groups = channel.getList("groups", Document.class, Collections.emptyList());
                    for (Document group : groups) {
                        List<String> strings = group.getList("strings", String.class, Collections.emptyList());
                        String match = matcher.group(group.getInteger("group"));
                        if (match != null && strings.contains(match)) {
                            matchCount++;
                        }
                    }
                    if (type == RegexType.INVITE) {
                        codes.add(matcher.group(1));
                    }
                    totalCount++;
                }
                if (matchCount == totalCount) {
                    continue;
                }
                CompletableFuture<Document> future;
                if (type == RegexType.INVITE) {
                    List<CompletableFuture<Invite>> futures = codes.stream().map(code -> Invite.resolve(message.getJDA(), code, true).submit()).collect(Collectors.toList());
                    List<Long> guilds = channel.getList("guilds", Long.class, Collections.emptyList());
                    future = FutureUtility.anyOf(futures, invite -> {
                        Invite.Guild inviteGuild = invite.getGuild();
                        return inviteGuild == null || (!guilds.contains(inviteGuild.getIdLong()) && inviteGuild.getIdLong() != guildId);
                    }).thenApply(invite -> invite == null ? null : regex);
                } else {
                    future = CompletableFuture.completedFuture(regex);
                }
                matches.add(future);
            }
            FutureUtility.anyOf(matches, Objects::nonNull).thenAccept(regex -> {
                if (regex == null) {
                    return;
                }
                ObjectId id = regex.getObjectId("_id");
                RegexType type = RegexType.fromId(regex.getInteger("type"));
                Document match = regex.get("match", MongoDatabase.EMPTY_DOCUMENT);
                long matchAction = match.get("action", MatchAction.ALL);
                Document mod = regex.get("mod", MongoDatabase.EMPTY_DOCUMENT);
                Document actionData = mod.get("action", Document.class);
                Action action = actionData == null ? null : Action.fromData(actionData);
                Document attempts = regex.get("attempts", MongoDatabase.EMPTY_DOCUMENT);
                int maxAttempts = attempts.get("amount", 3);
                if ((matchAction & MatchAction.DELETE_MESSAGE.getRaw()) == MatchAction.DELETE_MESSAGE.getRaw() && selfMember.hasPermission(messageChannel, Permission.MESSAGE_MANAGE)) {
                    message.delete().queue();
                }
                Document reset = attempts.get("reset", Document.class);
                List<Bson> update = List.of(Operators.set("attempts", Operators.let(new Document("attempts", Operators.ifNull("$attempts", 0)), Operators.cond(Operators.exists("$reset"), Operators.max(1, Operators.add(1, Operators.subtract("$$attempts", Operators.multiply(Operators.toInt(Operators.floor(Operators.divide(Operators.subtract(Operators.nowEpochSecond(), "$lastAttempt"), "$reset.after"))), "$reset.amount")))), Operators.add("$$attempts", 1)))), Operators.set("lastAttempt", Operators.nowEpochSecond()), Operators.setOnInsert("guildId", guildId), reset == null ? Operators.unset("reset") : Operators.set("reset", reset));
                Bson filter = Filters.and(Filters.eq("userId", userId), Filters.eq("regexId", id));
                FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).projection(Projections.include("attempts")).returnDocument(ReturnDocument.AFTER);
                this.bot.getMongo().findAndUpdateRegexAttempt(filter, update, options).whenComplete((attemptsData, attemptsException) -> {
                    if (ExceptionUtility.sendErrorMessage(attemptsException)) {
                        return;
                    }
                    int currentAttempts = attemptsData.getInteger("attempts", 0);
                    String matchMessage = this.format(match.get("message", type.getDefaultMatchMessage()), user, messageChannel, id, currentAttempts, maxAttempts, action);
                    String modMessage = this.format(mod.get("message", type.getDefaultModMessage()), user, messageChannel, id, currentAttempts, maxAttempts, action);
                    boolean send = (matchAction & MatchAction.SEND_MESSAGE.getRaw()) == MatchAction.SEND_MESSAGE.getRaw() && selfMember.hasPermission(messageChannel, Permission.MESSAGE_SEND);
                    if (action != null && currentAttempts == maxAttempts) {
                        Reason reason = new Reason(String.format("Sent a message which matched regex `%s` %d time%s", id.toHexString(), maxAttempts, maxAttempts == 1 ? "" : "s"));
                        ModUtility.performAction(this.bot, action, member, selfMember, reason).thenCompose(result -> {
                            if (send) {
                                messageChannel.sendMessage(modMessage).allowedMentions(EnumSet.allOf(Message.MentionType.class)).queue();
                            }
                            return this.bot.getMongo().deleteRegexAttempt(Filters.and(Filters.eq("userId", userId), Filters.eq("regexId", id)));
                        }).whenComplete((result, modException) -> {
                            Throwable cause = modException instanceof CompletionException ? modException.getCause() : modException;
                            if (cause instanceof ModException) {
                                messageChannel.sendMessage(modException.getMessage() + " " + this.bot.getConfig().getFailureEmote()).queue();
                                return;
                            }
                            ExceptionUtility.sendExceptionally(messageChannel, modException);
                        });
                        return;
                    }
                    if (send) {
                        messageChannel.sendMessage(matchMessage).allowedMentions(EnumSet.allOf(Message.MentionType.class)).queue();
                    }
                });
            });
        });
    });
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) ModException(com.sx4.bot.exceptions.mod.ModException) Permission(net.dv8tion.jda.api.Permission) MessageUpdateEvent(net.dv8tion.jda.api.events.message.MessageUpdateEvent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Bson(org.bson.conversions.Bson) Matcher(java.util.regex.Matcher) Sx4(com.sx4.bot.core.Sx4) Reason(com.sx4.bot.entities.mod.Reason) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Action(com.sx4.bot.entities.mod.action.Action) Operators(com.sx4.bot.database.mongo.model.Operators) java.util.concurrent(java.util.concurrent) ModUtility(com.sx4.bot.utility.ModUtility) WhitelistType(com.sx4.bot.entities.management.WhitelistType) Collectors(java.util.stream.Collectors) EventListener(net.dv8tion.jda.api.hooks.EventListener) StringFormatter(com.sx4.bot.formatter.StringFormatter) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) RegexType(com.sx4.bot.entities.mod.auto.RegexType) Pattern(java.util.regex.Pattern) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) NotNull(org.jetbrains.annotations.NotNull) RegexType(com.sx4.bot.entities.mod.auto.RegexType) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Action(com.sx4.bot.entities.mod.action.Action) Matcher(java.util.regex.Matcher) ModException(com.sx4.bot.exceptions.mod.ModException) Document(org.bson.Document) Reason(com.sx4.bot.entities.mod.Reason) Bson(org.bson.conversions.Bson) Pattern(java.util.regex.Pattern) ObjectId(org.bson.types.ObjectId)

Aggregations

com.mongodb.client.model (com.mongodb.client.model)1 Sx4 (com.sx4.bot.core.Sx4)1 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)1 Operators (com.sx4.bot.database.mongo.model.Operators)1 WhitelistType (com.sx4.bot.entities.management.WhitelistType)1 Reason (com.sx4.bot.entities.mod.Reason)1 Action (com.sx4.bot.entities.mod.action.Action)1 MatchAction (com.sx4.bot.entities.mod.auto.MatchAction)1 RegexType (com.sx4.bot.entities.mod.auto.RegexType)1 HolderType (com.sx4.bot.entities.settings.HolderType)1 ModException (com.sx4.bot.exceptions.mod.ModException)1 StringFormatter (com.sx4.bot.formatter.StringFormatter)1 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)1 FutureUtility (com.sx4.bot.utility.FutureUtility)1 ModUtility (com.sx4.bot.utility.ModUtility)1 java.util (java.util)1 java.util.concurrent (java.util.concurrent)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1