Search in sources :

Example 1 with TLongIntHashMap

use of gnu.trove.map.hash.TLongIntHashMap in project overflowdb by ShiftLeftSecurity.

the class NodesList method compact.

/**
 * trims down internal collections to just about the necessary size, in order to allow the remainder to be
 * garbage collected
 */
synchronized void compact() {
    final ArrayList<Node> newNodes = new ArrayList<>(size);
    Iterator<Node> iter = iterator();
    while (iter.hasNext()) {
        newNodes.add(iter.next());
    }
    nodes = newNodes.toArray(new Node[size]);
    // reindex helper collections
    emptySlots.clear();
    nodeIndexByNodeId = new TLongIntHashMap(this.nodes.length);
    int idx = 0;
    while (idx < this.nodes.length) {
        Node node = this.nodes[idx];
        nodeIndexByNodeId.put(node.id(), idx);
        idx++;
    }
}
Also used : TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) Node(overflowdb.Node)

Example 2 with TLongIntHashMap

use of gnu.trove.map.hash.TLongIntHashMap in project Sx4 by sx4-discord-bot.

the class LoggerHandler method onMessageBulkDelete.

public void onMessageBulkDelete(MessageBulkDeleteEvent event) {
    List<String> messageIds = event.getMessageIds();
    TextChannel textChannel = event.getChannel();
    Guild guild = event.getGuild();
    LoggerEvent loggerEvent = LoggerEvent.MESSAGE_DELETE;
    this.bot.getMongo().aggregateLoggers(this.getPipeline(guild.getIdLong())).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendErrorMessage(exception)) {
            return;
        }
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        if (guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
            this.retrieveAuditLogsDelayed(guild, ActionType.MESSAGE_BULK_DELETE).whenComplete((logs, auditException) -> {
                this.messageCache.putIfAbsent(guild.getIdLong(), new TLongIntHashMap());
                TLongIntMap guildCache = this.messageCache.get(guild.getIdLong());
                AuditLogEntry entry = logs == null ? null : logs.stream().filter(e -> Duration.between(e.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toMinutes() <= 5).filter(e -> {
                    int count = Integer.parseInt(e.getOptionByName("count"));
                    int oldCount = guildCache.get(e.getIdLong());
                    guildCache.put(e.getIdLong(), count);
                    return (count == messageIds.size() && count != oldCount) || count > oldCount;
                }).findFirst().orElse(null);
                this.handleBulkMessages(textChannel, messageIds, data.getList("loggers", Document.class), loggerEvent, entry == null ? null : entry.getUser());
            });
            return;
        }
        this.handleBulkMessages(textChannel, messageIds, data.getList("loggers", Document.class), loggerEvent, null);
    });
}
Also used : TLongIntMap(gnu.trove.map.TLongIntMap) MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) Document(org.bson.Document) PermissionOverrideCreateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideCreateEvent) RoleCreateEvent(net.dv8tion.jda.api.events.role.RoleCreateEvent) StoreChannelDeleteEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelDeleteEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Aggregates(com.mongodb.client.model.Aggregates) EmoteUpdateRolesEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateRolesEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) CategoryCreateEvent(net.dv8tion.jda.api.events.channel.category.CategoryCreateEvent) LoggerManager(com.sx4.bot.managers.LoggerManager) ColourUtility(com.sx4.bot.utility.ColourUtility) TextChannelDeleteEvent(net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent) EmoteAddedEvent(net.dv8tion.jda.api.events.emote.EmoteAddedEvent) TextChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.text.update.TextChannelUpdateNameEvent) TextChannelCreateEvent(net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent) Duration(java.time.Duration) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) LoggerContext(com.sx4.bot.entities.management.LoggerContext) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) AuditLogKey(net.dv8tion.jda.api.audit.AuditLogKey) PermissionOverrideDeleteEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideDeleteEvent) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) GuildMessageUpdateEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent) java.util.concurrent(java.util.concurrent) EmoteUpdateNameEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateNameEvent) CategoryDeleteEvent(net.dv8tion.jda.api.events.channel.category.CategoryDeleteEvent) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) GuildBanEvent(net.dv8tion.jda.api.events.guild.GuildBanEvent) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) EventListener(net.dv8tion.jda.api.hooks.EventListener) CategoryUpdateNameEvent(net.dv8tion.jda.api.events.channel.category.update.CategoryUpdateNameEvent) GuildMemberUpdateNicknameEvent(net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent) NotNull(org.jetbrains.annotations.NotNull) RoleUpdateColorEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateColorEvent) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) VoiceChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.voice.update.VoiceChannelUpdateNameEvent) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) RoleUpdatePermissionsEvent(net.dv8tion.jda.api.events.role.update.RoleUpdatePermissionsEvent) VoiceChannelDeleteEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelDeleteEvent) Projections(com.mongodb.client.model.Projections) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) Filters(com.mongodb.client.model.Filters) GuildMessageDeleteEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent) Bson(org.bson.conversions.Bson) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) EmoteRemovedEvent(net.dv8tion.jda.api.events.emote.EmoteRemovedEvent) Operators(com.sx4.bot.database.mongo.model.Operators) Accumulators(com.mongodb.client.model.Accumulators) TLongIntMap(gnu.trove.map.TLongIntMap) VoiceChannelCreateEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelCreateEvent) LoggerUtility(com.sx4.bot.utility.LoggerUtility) RoleUpdateNameEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateNameEvent) StoreChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.store.update.StoreChannelUpdateNameEvent) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) OkHttpClient(okhttp3.OkHttpClient) PermissionOverrideUpdateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideUpdateEvent) net.dv8tion.jda.api.events.guild.voice(net.dv8tion.jda.api.events.guild.voice) StoreChannelCreateEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelCreateEvent) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) GuildUnbanEvent(net.dv8tion.jda.api.events.guild.GuildUnbanEvent) TLongObjectMap(gnu.trove.map.TLongObjectMap) RoleDeleteEvent(net.dv8tion.jda.api.events.role.RoleDeleteEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) StringUtility(com.sx4.bot.utility.StringUtility) GuildMemberJoinEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) Document(org.bson.Document)

Example 3 with TLongIntHashMap

use of gnu.trove.map.hash.TLongIntHashMap in project Sx4 by sx4-discord-bot.

the class LoggerHandler method onGuildVoiceLeave.

public void onGuildVoiceLeave(GuildVoiceLeaveEvent event) {
    Guild guild = event.getGuild();
    Member member = event.getMember();
    User user = member.getUser();
    VoiceChannel channel = event.getChannelLeft();
    LoggerContext loggerContext = new LoggerContext().setChannel(channel).setUser(user);
    WebhookEmbedBuilder embed = new WebhookEmbedBuilder();
    embed.setDescription(String.format("`%s` just left the voice channel %s", member.getEffectiveName(), channel.getAsMention()));
    embed.setColor(this.bot.getConfig().getRed());
    embed.setTimestamp(Instant.now());
    embed.setAuthor(new EmbedAuthor(user.getAsTag(), user.getEffectiveAvatarUrl(), null));
    embed.setFooter(new EmbedFooter(String.format("User ID: %s", user.getId()), null));
    this.bot.getMongo().aggregateLoggers(this.getPipeline(guild.getIdLong())).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendErrorMessage(exception)) {
            return;
        }
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        List<Document> loggers = data.getList("loggers", Document.class);
        if (loggers.isEmpty()) {
            return;
        }
        if (guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
            this.retrieveAuditLogsDelayed(event.getGuild(), ActionType.MEMBER_VOICE_KICK).whenComplete((logs, auditException) -> {
                this.disconnectCache.putIfAbsent(guild.getIdLong(), new TLongIntHashMap());
                TLongIntMap guildCache = this.disconnectCache.get(guild.getIdLong());
                AuditLogEntry entry = logs == null ? null : logs.stream().filter(e -> Duration.between(e.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toMinutes() <= 10).filter(e -> {
                    int count = Integer.parseInt(e.getOptionByName("count"));
                    int oldCount = guildCache.get(e.getIdLong());
                    guildCache.put(e.getIdLong(), count);
                    return (count == 1 && count != oldCount) || count > oldCount;
                }).findFirst().orElse(null);
                User moderator = entry == null ? null : entry.getUser();
                LoggerEvent loggerEvent = moderator == null ? LoggerEvent.MEMBER_VOICE_LEAVE : LoggerEvent.MEMBER_VOICE_DISCONNECT;
                if (moderator != null) {
                    loggerContext.setModerator(moderator);
                    embed.setDescription(String.format("`%s` was disconnected from the voice channel %s by **%s**", member.getEffectiveName(), channel.getAsMention(), moderator.getAsTag()));
                }
                this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
            });
        } else {
            LoggerEvent loggerEvent = LoggerEvent.MEMBER_VOICE_LEAVE;
            this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
        }
    });
}
Also used : TLongIntMap(gnu.trove.map.TLongIntMap) MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) Document(org.bson.Document) PermissionOverrideCreateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideCreateEvent) RoleCreateEvent(net.dv8tion.jda.api.events.role.RoleCreateEvent) StoreChannelDeleteEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelDeleteEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Aggregates(com.mongodb.client.model.Aggregates) EmoteUpdateRolesEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateRolesEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) CategoryCreateEvent(net.dv8tion.jda.api.events.channel.category.CategoryCreateEvent) LoggerManager(com.sx4.bot.managers.LoggerManager) ColourUtility(com.sx4.bot.utility.ColourUtility) TextChannelDeleteEvent(net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent) EmoteAddedEvent(net.dv8tion.jda.api.events.emote.EmoteAddedEvent) TextChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.text.update.TextChannelUpdateNameEvent) TextChannelCreateEvent(net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent) Duration(java.time.Duration) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) LoggerContext(com.sx4.bot.entities.management.LoggerContext) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) AuditLogKey(net.dv8tion.jda.api.audit.AuditLogKey) PermissionOverrideDeleteEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideDeleteEvent) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) GuildMessageUpdateEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent) java.util.concurrent(java.util.concurrent) EmoteUpdateNameEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateNameEvent) CategoryDeleteEvent(net.dv8tion.jda.api.events.channel.category.CategoryDeleteEvent) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) GuildBanEvent(net.dv8tion.jda.api.events.guild.GuildBanEvent) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) EventListener(net.dv8tion.jda.api.hooks.EventListener) CategoryUpdateNameEvent(net.dv8tion.jda.api.events.channel.category.update.CategoryUpdateNameEvent) GuildMemberUpdateNicknameEvent(net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent) NotNull(org.jetbrains.annotations.NotNull) RoleUpdateColorEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateColorEvent) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) VoiceChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.voice.update.VoiceChannelUpdateNameEvent) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) RoleUpdatePermissionsEvent(net.dv8tion.jda.api.events.role.update.RoleUpdatePermissionsEvent) VoiceChannelDeleteEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelDeleteEvent) Projections(com.mongodb.client.model.Projections) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) Filters(com.mongodb.client.model.Filters) GuildMessageDeleteEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent) Bson(org.bson.conversions.Bson) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) EmoteRemovedEvent(net.dv8tion.jda.api.events.emote.EmoteRemovedEvent) Operators(com.sx4.bot.database.mongo.model.Operators) Accumulators(com.mongodb.client.model.Accumulators) TLongIntMap(gnu.trove.map.TLongIntMap) VoiceChannelCreateEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelCreateEvent) LoggerUtility(com.sx4.bot.utility.LoggerUtility) RoleUpdateNameEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateNameEvent) StoreChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.store.update.StoreChannelUpdateNameEvent) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) OkHttpClient(okhttp3.OkHttpClient) PermissionOverrideUpdateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideUpdateEvent) net.dv8tion.jda.api.events.guild.voice(net.dv8tion.jda.api.events.guild.voice) StoreChannelCreateEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelCreateEvent) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) GuildUnbanEvent(net.dv8tion.jda.api.events.guild.GuildUnbanEvent) TLongObjectMap(gnu.trove.map.TLongObjectMap) RoleDeleteEvent(net.dv8tion.jda.api.events.role.RoleDeleteEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) StringUtility(com.sx4.bot.utility.StringUtility) GuildMemberJoinEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) Document(org.bson.Document) LoggerContext(com.sx4.bot.entities.management.LoggerContext) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Example 4 with TLongIntHashMap

use of gnu.trove.map.hash.TLongIntHashMap in project olca-modules by GreenDelta.

the class FlowTable method directionsOf.

/**
 * Try to determine the (impact) directions of the given flows. Returns a map
 * that associates an integer value $v$ to each flow ID. A value $v < 0$ means
 * that the corresponding flow is an input flow and a value $v > 0$ that it is
 * an output flow. The larger $|v|$ is the more certain is this classification.
 * A value of $v = 0$ means that the flow direction cannot be determined from
 * the information in the database. Also, product and waste flows will always
 * have a value of $v = 0$ as these flows can always occur on the input or
 * output side of processes.
 */
public static TLongIntHashMap directionsOf(IDatabase db, Iterable<FlowDescriptor> flows) {
    // initialize the map
    var map = new TLongIntHashMap();
    if (db == null || flows == null)
        return map;
    for (var flow : flows) {
        if (flow.flowType == FlowType.ELEMENTARY_FLOW) {
            map.put(flow.id, 0);
        }
    }
    // try to get the flow directions from the exchanges
    var sql = "select f_flow, is_input from tbl_exchanges";
    NativeSql.on(db).query(sql, r -> {
        var id = r.getLong(1);
        if (!map.containsKey(id))
            return true;
        var isInput = r.getBoolean(2);
        var current = map.get(id);
        map.put(id, isInput ? current - 1 : current + 1);
        return true;
    });
    // check if there are v = 0 cases
    var withZero = new TLongHashSet();
    for (var mapIt = map.iterator(); mapIt.hasNext(); ) {
        mapIt.advance();
        if (mapIt.value() == 0) {
            withZero.add(mapIt.key());
        }
    }
    if (withZero.isEmpty())
        return map;
    // try to determine it from the category path
    var categories = Categories.pathsOf(db);
    for (var flow : flows) {
        if (!withZero.contains(flow.id) || flow.category == null)
            continue;
        var path = categories.pathOf(flow.category);
        if (path == null)
            continue;
        path = path.toLowerCase();
        if (path.contains("resource")) {
            withZero.remove(flow.id);
            map.put(flow.id, -1);
        } else if (path.contains("emission")) {
            withZero.remove(flow.id);
            map.put(flow.id, +1);
        }
    }
    if (withZero.isEmpty())
        return map;
    // try to determine it from other flows that are
    // used in the same impact categories
    var zeroToImpacts = new TLongObjectHashMap<TLongHashSet>();
    var impactTotals = new TLongIntHashMap();
    sql = "select f_impact_category, f_flow from tbl_impact_factors";
    NativeSql.on(db).query(sql, r -> {
        var impact = r.getLong(1);
        var flow = r.getLong(2);
        // add zero-flow impact link
        if (withZero.contains(flow)) {
            var flowImpacts = zeroToImpacts.get(flow);
            if (flowImpacts == null) {
                flowImpacts = new TLongHashSet();
                zeroToImpacts.put(flow, flowImpacts);
            }
            flowImpacts.add(impact);
            return true;
        }
        // add flow direction to impact direction
        var flowVal = map.get(flow);
        if (flowVal != 0) {
            var total = impactTotals.get(impact);
            impactTotals.put(impact, total + flowVal);
        }
        return true;
    });
    for (var it = withZero.iterator(); it.hasNext(); ) {
        var zeroID = it.next();
        var impacts = zeroToImpacts.get(zeroID);
        if (impacts == null)
            continue;
        var val = 0;
        for (var impactIt = impacts.iterator(); impactIt.hasNext(); ) {
            val += impactTotals.get(impactIt.next());
        }
        if (val != 0) {
            map.put(zeroID, val < 0 ? -1 : 1);
        }
    }
    return map;
}
Also used : TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) TLongHashSet(gnu.trove.set.hash.TLongHashSet) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap)

Example 5 with TLongIntHashMap

use of gnu.trove.map.hash.TLongIntHashMap in project Sx4 by sx4-discord-bot.

the class LoggerHandler method onGuildMessageDelete.

public void onGuildMessageDelete(GuildMessageDeleteEvent event) {
    TextChannel channel = event.getChannel();
    Guild guild = event.getGuild();
    LoggerEvent loggerEvent = LoggerEvent.MESSAGE_DELETE;
    LoggerContext loggerContext = new LoggerContext().setChannel(channel);
    GuildMessage message = this.bot.getMessageCache().getMessageById(event.getMessageIdLong());
    if (message != null) {
        loggerContext.setUser(message.getAuthor());
    }
    this.bot.getMongo().aggregateLoggers(this.getPipeline(guild.getIdLong())).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendErrorMessage(exception)) {
            return;
        }
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        List<Document> loggers = LoggerUtility.getValidLoggers(data.getList("loggers", Document.class), loggerEvent, loggerContext);
        if (loggers.isEmpty()) {
            return;
        }
        WebhookEmbedBuilder embed = new WebhookEmbedBuilder().setColor(this.bot.getConfig().getRed()).setTimestamp(Instant.now()).setFooter(new EmbedFooter("Message ID: " + event.getMessageId(), null));
        StringBuilder description = new StringBuilder();
        if (message == null) {
            description.append(String.format("A message sent in %s was deleted", channel.getAsMention()));
            embed.setAuthor(new EmbedAuthor(guild.getName(), guild.getIconUrl(), null));
        } else {
            User author = message.getAuthor();
            description.append(String.format("The message sent by `%s` in %s was deleted", author.getAsTag(), channel.getAsMention()));
            embed.setAuthor(new EmbedAuthor(author.getAsTag(), author.getEffectiveAvatarUrl(), null));
            String content = message.getContent();
            if (!content.isBlank()) {
                embed.addField(new EmbedField(false, "Message", StringUtility.limit(content, MessageEmbed.VALUE_MAX_LENGTH, "...")));
            }
        }
        if (guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
            this.retrieveAuditLogsDelayed(guild, ActionType.MESSAGE_DELETE).whenComplete((logs, auditException) -> {
                this.messageCache.putIfAbsent(guild.getIdLong(), new TLongIntHashMap());
                TLongIntMap guildCache = this.messageCache.get(guild.getIdLong());
                AuditLogEntry entry = logs == null ? null : logs.stream().filter(e -> Duration.between(e.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toMinutes() <= 5).filter(e -> Long.parseLong(e.getOptionByName("channel_id")) == channel.getIdLong()).filter(e -> {
                    int count = Integer.parseInt(e.getOptionByName("count"));
                    int oldCount = guildCache.get(e.getIdLong());
                    guildCache.put(e.getIdLong(), count);
                    return (count == 1 && count != oldCount) || count > oldCount;
                }).findFirst().orElse(null);
                User moderator = entry == null ? null : entry.getUser();
                if (moderator != null) {
                    loggerContext.setModerator(moderator);
                    description.append(" by **").append(moderator.getAsTag()).append("**");
                }
                embed.setDescription(description.toString());
                this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
            });
            return;
        }
        embed.setDescription(description.toString());
        this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
    });
}
Also used : TLongIntMap(gnu.trove.map.TLongIntMap) MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) Document(org.bson.Document) PermissionOverrideCreateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideCreateEvent) RoleCreateEvent(net.dv8tion.jda.api.events.role.RoleCreateEvent) StoreChannelDeleteEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelDeleteEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Aggregates(com.mongodb.client.model.Aggregates) EmoteUpdateRolesEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateRolesEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) CategoryCreateEvent(net.dv8tion.jda.api.events.channel.category.CategoryCreateEvent) LoggerManager(com.sx4.bot.managers.LoggerManager) ColourUtility(com.sx4.bot.utility.ColourUtility) TextChannelDeleteEvent(net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent) EmoteAddedEvent(net.dv8tion.jda.api.events.emote.EmoteAddedEvent) TextChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.text.update.TextChannelUpdateNameEvent) TextChannelCreateEvent(net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent) Duration(java.time.Duration) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) LoggerContext(com.sx4.bot.entities.management.LoggerContext) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) AuditLogKey(net.dv8tion.jda.api.audit.AuditLogKey) PermissionOverrideDeleteEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideDeleteEvent) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) GuildMessageUpdateEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent) java.util.concurrent(java.util.concurrent) EmoteUpdateNameEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateNameEvent) CategoryDeleteEvent(net.dv8tion.jda.api.events.channel.category.CategoryDeleteEvent) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) GuildBanEvent(net.dv8tion.jda.api.events.guild.GuildBanEvent) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) EventListener(net.dv8tion.jda.api.hooks.EventListener) CategoryUpdateNameEvent(net.dv8tion.jda.api.events.channel.category.update.CategoryUpdateNameEvent) GuildMemberUpdateNicknameEvent(net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent) NotNull(org.jetbrains.annotations.NotNull) RoleUpdateColorEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateColorEvent) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) VoiceChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.voice.update.VoiceChannelUpdateNameEvent) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) RoleUpdatePermissionsEvent(net.dv8tion.jda.api.events.role.update.RoleUpdatePermissionsEvent) VoiceChannelDeleteEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelDeleteEvent) Projections(com.mongodb.client.model.Projections) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) Filters(com.mongodb.client.model.Filters) GuildMessageDeleteEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent) Bson(org.bson.conversions.Bson) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) EmoteRemovedEvent(net.dv8tion.jda.api.events.emote.EmoteRemovedEvent) Operators(com.sx4.bot.database.mongo.model.Operators) Accumulators(com.mongodb.client.model.Accumulators) TLongIntMap(gnu.trove.map.TLongIntMap) VoiceChannelCreateEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelCreateEvent) LoggerUtility(com.sx4.bot.utility.LoggerUtility) RoleUpdateNameEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateNameEvent) StoreChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.store.update.StoreChannelUpdateNameEvent) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) OkHttpClient(okhttp3.OkHttpClient) PermissionOverrideUpdateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideUpdateEvent) net.dv8tion.jda.api.events.guild.voice(net.dv8tion.jda.api.events.guild.voice) StoreChannelCreateEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelCreateEvent) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) GuildUnbanEvent(net.dv8tion.jda.api.events.guild.GuildUnbanEvent) TLongObjectMap(gnu.trove.map.TLongObjectMap) RoleDeleteEvent(net.dv8tion.jda.api.events.role.RoleDeleteEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) StringUtility(com.sx4.bot.utility.StringUtility) GuildMemberJoinEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) Document(org.bson.Document) LoggerContext(com.sx4.bot.entities.management.LoggerContext) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Aggregations

TLongIntHashMap (gnu.trove.map.hash.TLongIntHashMap)9 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)5 Collectors (java.util.stream.Collectors)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 EmbedAuthor (club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor)4 EmbedField (club.minnced.discord.webhook.send.WebhookEmbed.EmbedField)4 EmbedFooter (club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter)4 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)4 Accumulators (com.mongodb.client.model.Accumulators)4 Aggregates (com.mongodb.client.model.Aggregates)4 Filters (com.mongodb.client.model.Filters)4 Projections (com.mongodb.client.model.Projections)4 Sx4 (com.sx4.bot.core.Sx4)4 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)4 Operators (com.sx4.bot.database.mongo.model.Operators)4 GuildMessage (com.sx4.bot.entities.cache.GuildMessage)4 LoggerContext (com.sx4.bot.entities.management.LoggerContext)4 LoggerEvent (com.sx4.bot.entities.management.LoggerEvent)4 LoggerManager (com.sx4.bot.managers.LoggerManager)4 ColourUtility (com.sx4.bot.utility.ColourUtility)4