Search in sources :

Example 1 with SnowflakeCacheViewImpl

use of net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl in project JDA by DV8FromTheWorld.

the class EntityBuilder method createGuild.

public GuildImpl createGuild(long guildId, DataObject guildJson, TLongObjectMap<DataObject> members, int memberCount) {
    final GuildImpl guildObj = new GuildImpl(getJDA(), guildId);
    final String name = guildJson.getString("name", "");
    final String iconId = guildJson.getString("icon", null);
    final String splashId = guildJson.getString("splash", null);
    final String description = guildJson.getString("description", null);
    final String vanityCode = guildJson.getString("vanity_url_code", null);
    final String bannerId = guildJson.getString("banner", null);
    final String locale = guildJson.getString("preferred_locale", "en-US");
    final DataArray roleArray = guildJson.getArray("roles");
    final DataArray channelArray = guildJson.getArray("channels");
    final DataArray threadArray = guildJson.getArray("threads");
    final DataArray emotesArray = guildJson.getArray("emojis");
    final DataArray voiceStateArray = guildJson.getArray("voice_states");
    final Optional<DataArray> featuresArray = guildJson.optArray("features");
    final Optional<DataArray> presencesArray = guildJson.optArray("presences");
    final long ownerId = guildJson.getUnsignedLong("owner_id", 0L);
    final long afkChannelId = guildJson.getUnsignedLong("afk_channel_id", 0L);
    final long systemChannelId = guildJson.getUnsignedLong("system_channel_id", 0L);
    final long rulesChannelId = guildJson.getUnsignedLong("rules_channel_id", 0L);
    final long communityUpdatesChannelId = guildJson.getUnsignedLong("public_updates_channel_id", 0L);
    final int boostCount = guildJson.getInt("premium_subscription_count", 0);
    final int boostTier = guildJson.getInt("premium_tier", 0);
    final int maxMembers = guildJson.getInt("max_members", 0);
    final int maxPresences = guildJson.getInt("max_presences", 5000);
    final int mfaLevel = guildJson.getInt("mfa_level", 0);
    final int afkTimeout = guildJson.getInt("afk_timeout", 0);
    final int verificationLevel = guildJson.getInt("verification_level", 0);
    final int notificationLevel = guildJson.getInt("default_message_notifications", 0);
    final int explicitContentLevel = guildJson.getInt("explicit_content_filter", 0);
    final int nsfwLevel = guildJson.getInt("nsfw_level", -1);
    final boolean boostProgressBarEnabled = guildJson.getBoolean("premium_progress_bar_enabled");
    guildObj.setName(name).setIconId(iconId).setSplashId(splashId).setDescription(description).setBannerId(bannerId).setVanityCode(vanityCode).setMaxMembers(maxMembers).setMaxPresences(maxPresences).setOwnerId(ownerId).setAfkTimeout(Guild.Timeout.fromKey(afkTimeout)).setVerificationLevel(VerificationLevel.fromKey(verificationLevel)).setDefaultNotificationLevel(Guild.NotificationLevel.fromKey(notificationLevel)).setExplicitContentLevel(Guild.ExplicitContentLevel.fromKey(explicitContentLevel)).setRequiredMFALevel(Guild.MFALevel.fromKey(mfaLevel)).setLocale(locale).setBoostCount(boostCount).setBoostTier(boostTier).setMemberCount(memberCount).setNSFWLevel(Guild.NSFWLevel.fromKey(nsfwLevel)).setBoostProgressBarEnabled(boostProgressBarEnabled);
    SnowflakeCacheViewImpl<Guild> guildView = getJDA().getGuildsView();
    try (UnlockHook hook = guildView.writeLock()) {
        guildView.getMap().put(guildId, guildObj);
    }
    guildObj.setFeatures(featuresArray.map(it -> StreamSupport.stream(it.spliterator(), false).map(String::valueOf).collect(Collectors.toSet())).orElse(Collections.emptySet()));
    SnowflakeCacheViewImpl<Role> roleView = guildObj.getRolesView();
    try (UnlockHook hook = roleView.writeLock()) {
        TLongObjectMap<Role> map = roleView.getMap();
        for (int i = 0; i < roleArray.length(); i++) {
            DataObject obj = roleArray.getObject(i);
            Role role = createRole(guildObj, obj, guildId);
            map.put(role.getIdLong(), role);
            if (role.getIdLong() == guildObj.getIdLong())
                guildObj.setPublicRole(role);
        }
    }
    for (int i = 0; i < channelArray.length(); i++) {
        DataObject channelJson = channelArray.getObject(i);
        createGuildChannel(guildObj, channelJson);
    }
    TLongObjectMap<DataObject> voiceStates = convertToUserMap((o) -> o.getUnsignedLong("user_id", 0L), voiceStateArray);
    TLongObjectMap<DataObject> presences = presencesArray.map(o1 -> convertToUserMap(o2 -> o2.getObject("user").getUnsignedLong("id"), o1)).orElseGet(TLongObjectHashMap::new);
    try (UnlockHook h1 = guildObj.getMembersView().writeLock();
        UnlockHook h2 = getJDA().getUsersView().writeLock()) {
        // this is done because we can still keep track of members in voice channels
        for (DataObject memberJson : members.valueCollection()) {
            long userId = memberJson.getObject("user").getUnsignedLong("id");
            DataObject voiceState = voiceStates.get(userId);
            DataObject presence = presences.get(userId);
            updateMemberCache(createMember(guildObj, memberJson, voiceState, presence));
        }
    }
    if (guildObj.getOwner() == null)
        LOG.debug("Finished setup for guild with a null owner. GuildId: {} OwnerId: {}", guildId, guildJson.opt("owner_id").orElse(null));
    if (guildObj.getMember(api.getSelfUser()) == null) {
        LOG.error("Guild is missing a SelfMember. GuildId: {}", guildId);
        LOG.debug("Guild is missing a SelfMember. GuildId: {} JSON: \n{}", guildId, guildJson);
        // This is actually a gateway request
        guildObj.retrieveMembersByIds(api.getSelfUser().getIdLong()).onSuccess(m -> {
            if (m.isEmpty())
                LOG.warn("Was unable to recover SelfMember for guild with id {}. This guild might be corrupted!", guildId);
            else
                LOG.debug("Successfully recovered SelfMember for guild with id {}.", guildId);
        });
    }
    for (int i = 0; i < threadArray.length(); i++) {
        DataObject threadJson = threadArray.getObject(i);
        createThreadChannel(guildObj, threadJson, guildObj.getIdLong());
    }
    createGuildEmotePass(guildObj, emotesArray);
    guildJson.optArray("stage_instances").map(arr -> arr.stream(DataArray::getObject)).ifPresent(list -> list.forEach(it -> createStageInstance(guildObj, it)));
    guildObj.setAfkChannel(guildObj.getVoiceChannelById(afkChannelId)).setSystemChannel(guildObj.getTextChannelById(systemChannelId)).setRulesChannel(guildObj.getTextChannelById(rulesChannelId)).setCommunityUpdatesChannel(guildObj.getTextChannelById(communityUpdatesChannelId));
    return guildObj;
}
Also used : MemberCacheViewImpl(net.dv8tion.jda.internal.utils.cache.MemberCacheViewImpl) NotificationLevel(net.dv8tion.jda.api.entities.Guild.NotificationLevel) ExplicitContentLevel(net.dv8tion.jda.api.entities.Guild.ExplicitContentLevel) UnaryOperator(java.util.function.UnaryOperator) UserUpdateAvatarEvent(net.dv8tion.jda.api.events.user.update.UserUpdateAvatarEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) UserUpdateFlagsEvent(net.dv8tion.jda.api.events.user.update.UserUpdateFlagsEvent) TLongHashSet(gnu.trove.set.hash.TLongHashSet) JDAImpl(net.dv8tion.jda.internal.JDAImpl) EventCache(net.dv8tion.jda.internal.handle.EventCache) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) VerificationLevel(net.dv8tion.jda.api.entities.Guild.VerificationLevel) DataObject(net.dv8tion.jda.api.utils.data.DataObject) ToLongFunction(java.util.function.ToLongFunction) AudioChannelMixin(net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin) OnlineStatus(net.dv8tion.jda.api.OnlineStatus) TLongSet(gnu.trove.set.TLongSet) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) OffsetDateTime(java.time.OffsetDateTime) JDALogger(net.dv8tion.jda.internal.utils.JDALogger) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) DataArray(net.dv8tion.jda.api.utils.data.DataArray) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) Helpers(net.dv8tion.jda.internal.utils.Helpers) Timeout(net.dv8tion.jda.api.entities.Guild.Timeout) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) CaseInsensitiveMap(org.apache.commons.collections4.map.CaseInsensitiveMap) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) TemporalAccessor(java.time.temporal.TemporalAccessor) Template(net.dv8tion.jda.api.entities.templates.Template) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) UserUpdateDiscriminatorEvent(net.dv8tion.jda.api.events.user.update.UserUpdateDiscriminatorEvent) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) StreamSupport(java.util.stream.StreamSupport) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) TemplateChannel(net.dv8tion.jda.api.entities.templates.TemplateChannel) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) Logger(org.slf4j.Logger) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) UserUpdateNameEvent(net.dv8tion.jda.api.events.user.update.UserUpdateNameEvent) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TemplateGuild(net.dv8tion.jda.api.entities.templates.TemplateGuild) DateTimeFormatter(java.time.format.DateTimeFormatter) TLongObjectMap(gnu.trove.map.TLongObjectMap) net.dv8tion.jda.api.events.guild.member.update(net.dv8tion.jda.api.events.guild.member.update) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) IPermissionContainerMixin(net.dv8tion.jda.internal.entities.mixin.channel.attribute.IPermissionContainerMixin) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TemplateGuild(net.dv8tion.jda.api.entities.templates.TemplateGuild) DataArray(net.dv8tion.jda.api.utils.data.DataArray) TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) DataObject(net.dv8tion.jda.api.utils.data.DataObject) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook)

Example 2 with SnowflakeCacheViewImpl

use of net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl in project JDA by DV8FromTheWorld.

the class ChannelDeleteHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    ChannelType type = ChannelType.fromId(content.getInt("type"));
    long guildId = 0;
    if (type.isGuild()) {
        guildId = content.getLong("guild_id");
        if (getJDA().getGuildSetupController().isLocked(guildId))
            return guildId;
    }
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    final long channelId = content.getLong("id");
    switch(type) {
        case TEXT:
            {
                TextChannel channel = getJDA().getTextChannelsView().remove(channelId);
                if (channel == null || guild == null) {
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a text channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                guild.getTextChannelsView().remove(channel.getIdLong());
                getJDA().handleEvent(new ChannelDeleteEvent(getJDA(), responseNumber, channel));
                break;
            }
        case NEWS:
            {
                NewsChannel channel = getJDA().getNewsChannelView().remove(channelId);
                if (channel == null || guild == null) {
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a news channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                guild.getNewsChannelView().remove(channel.getIdLong());
                getJDA().handleEvent(new ChannelDeleteEvent(getJDA(), responseNumber, channel));
                break;
            }
        case VOICE:
            {
                VoiceChannel channel = getJDA().getVoiceChannelsView().remove(channelId);
                if (channel == null || guild == null) {
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a voice channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                // This is done in the AudioWebSocket already
                // //We use this instead of getAudioManager(Guild) so we don't create a new instance. Efficiency!
                // AudioManagerImpl manager = (AudioManagerImpl) getJDA().getAudioManagersView().get(guild.getIdLong());
                // if (manager != null && manager.isConnected()
                // && manager.getConnectedChannel().getIdLong() == channel.getIdLong())
                // {
                // manager.closeAudioConnection(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
                // }
                guild.getVoiceChannelsView().remove(channel.getIdLong());
                getJDA().handleEvent(new ChannelDeleteEvent(getJDA(), responseNumber, channel));
                break;
            }
        case STAGE:
            {
                StageChannel channel = getJDA().getStageChannelView().remove(channelId);
                if (channel == null || guild == null) {
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a stage channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                guild.getStageChannelsView().remove(channel.getIdLong());
                getJDA().handleEvent(new ChannelDeleteEvent(getJDA(), responseNumber, channel));
            }
        case CATEGORY:
            {
                Category category = getJDA().getCategoriesView().remove(channelId);
                if (category == null || guild == null) {
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a category channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                guild.getCategoriesView().remove(channelId);
                getJDA().handleEvent(new ChannelDeleteEvent(getJDA(), responseNumber, category));
                break;
            }
        case PRIVATE:
            {
                SnowflakeCacheViewImpl<PrivateChannel> privateView = getJDA().getPrivateChannelsView();
                PrivateChannel channel = privateView.remove(channelId);
                if (channel == null) {
                    // getJDA().getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent));
                    WebSocketClient.LOG.debug("CHANNEL_DELETE attempted to delete a private channel that is not yet cached. JSON: {}", content);
                    return null;
                }
                break;
            }
        case GROUP:
            WebSocketClient.LOG.warn("Received a CHANNEL_DELETE for a channel of type GROUP which is not supported!");
            return null;
        default:
            WebSocketClient.LOG.debug("CHANNEL_DELETE provided an unknown channel type. JSON: {}", content);
    }
    getJDA().getEventCache().clear(EventCache.Type.CHANNEL, channelId);
    return null;
}
Also used : GuildImpl(net.dv8tion.jda.internal.entities.GuildImpl) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) ChannelDeleteEvent(net.dv8tion.jda.api.events.channel.ChannelDeleteEvent)

Example 3 with SnowflakeCacheViewImpl

use of net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl in project JDA by DV8FromTheWorld.

the class GuildMemberRemoveHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    final long id = content.getLong("guild_id");
    boolean setup = getJDA().getGuildSetupController().onRemoveMember(id, content);
    if (setup)
        return null;
    GuildImpl guild = (GuildImpl) getJDA().getGuildsView().get(id);
    if (guild == null) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    final long userId = content.getObject("user").getUnsignedLong("id");
    if (userId == getJDA().getSelfUser().getIdLong()) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    // Update the memberCount
    guild.onMemberRemove();
    CacheView.SimpleCacheView<MemberPresenceImpl> presences = guild.getPresenceView();
    if (presences != null)
        presences.remove(userId);
    User user = api.getEntityBuilder().createUser(content.getObject("user"));
    MemberImpl member = (MemberImpl) guild.getMembersView().remove(userId);
    if (member == null) {
        // WebSocketClient.LOG.debug("Received GUILD_MEMBER_REMOVE for a Member that does not exist in the specified Guild. UserId: {} GuildId: {}", userId, id);
        // Remove user from voice channel if applicable
        guild.getVoiceChannelsView().forEachUnordered((channel) -> {
            VoiceChannelImpl impl = (VoiceChannelImpl) channel;
            Member connected = impl.getConnectedMembersMap().remove(userId);
            if (// user left channel!
            connected != null) {
                getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, connected, channel));
            }
        });
        // Fire cache independent event, we can still inform the library user about the member removal
        getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, null));
        return null;
    }
    GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
    if (// If this user was in an AudioChannel, fire VoiceLeaveEvent.
    voiceState != null && voiceState.inAudioChannel()) {
        AudioChannel channel = voiceState.getChannel();
        voiceState.setConnectedChannel(null);
        ((AudioChannelMixin<?>) channel).getConnectedMembersMap().remove(userId);
        getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, member, channel));
    }
    // The user is not in a different guild that we share
    SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
    try (UnlockHook hook = userView.writeLock()) {
        if (// don't remove selfUser from cache
        userId != getJDA().getSelfUser().getIdLong() && getJDA().getGuildsView().stream().noneMatch(g -> g.getMemberById(userId) != null)) {
            userView.remove(userId);
            getJDA().getEventCache().clear(EventCache.Type.USER, userId);
        }
    }
    // Cache independent event
    getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, member));
    return null;
}
Also used : GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) net.dv8tion.jda.internal.entities(net.dv8tion.jda.internal.entities) JDAImpl(net.dv8tion.jda.internal.JDAImpl) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) Member(net.dv8tion.jda.api.entities.Member) DataObject(net.dv8tion.jda.api.utils.data.DataObject) User(net.dv8tion.jda.api.entities.User) AudioChannelMixin(net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) User(net.dv8tion.jda.api.entities.User) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) Member(net.dv8tion.jda.api.entities.Member)

Example 4 with SnowflakeCacheViewImpl

use of net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl in project GeyserDiscordBot by GeyserMC.

the class LevelInfo method getUser.

public User getUser() {
    // Get the user from the cache
    User user = GeyserBot.getJDA().getUserById(userId);
    // Get the user from the API since it wasn't in the cache
    if (user == null) {
        user = GeyserBot.getJDA().retrieveUserById(userId).complete();
        // Add the user to the user cache since JDA doesn't do that
        SnowflakeCacheViewImpl<User> usersView = (SnowflakeCacheViewImpl<User>) GeyserBot.getJDA().getUserCache();
        try (UnlockHook hook = usersView.writeLock()) {
            usersView.getMap().put(user.getIdLong(), user);
        }
    }
    return user;
}
Also used : SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) User(net.dv8tion.jda.api.entities.User) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook)

Aggregations

SnowflakeCacheViewImpl (net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl)3 User (net.dv8tion.jda.api.entities.User)2 UnlockHook (net.dv8tion.jda.internal.utils.UnlockHook)2 TLongObjectMap (gnu.trove.map.TLongObjectMap)1 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)1 TLongSet (gnu.trove.set.TLongSet)1 TLongHashSet (gnu.trove.set.hash.TLongHashSet)1 Instant (java.time.Instant)1 OffsetDateTime (java.time.OffsetDateTime)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 TemporalAccessor (java.time.temporal.TemporalAccessor)1 java.util (java.util)1 Function (java.util.function.Function)1 ToLongFunction (java.util.function.ToLongFunction)1 UnaryOperator (java.util.function.UnaryOperator)1 Collectors (java.util.stream.Collectors)1 StreamSupport (java.util.stream.StreamSupport)1 Nonnull (javax.annotation.Nonnull)1 Nullable (javax.annotation.Nullable)1 JDA (net.dv8tion.jda.api.JDA)1