Search in sources :

Example 46 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class GuildMembersChunkHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    final long guildId = content.getLong("guild_id");
    DataArray members = content.getArray("members");
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild != null) {
        if (api.getClient().getChunkManager().handleChunk(guildId, content))
            return null;
        WebSocketClient.LOG.debug("Received member chunk for guild that is already in cache. GuildId: {} Count: {} Index: {}/{}", guildId, members.length(), content.getInt("chunk_index"), content.getInt("chunk_count"));
        // Chunk handling
        EntityBuilder builder = getJDA().getEntityBuilder();
        TLongObjectMap<DataObject> presences = content.optArray("presences").map(it -> builder.convertToUserMap(o -> o.getObject("user").getUnsignedLong("id"), it)).orElseGet(TLongObjectHashMap::new);
        for (int i = 0; i < members.length(); i++) {
            DataObject object = members.getObject(i);
            long userId = object.getObject("user").getUnsignedLong("id");
            DataObject presence = presences.get(userId);
            MemberImpl member = builder.createMember(guild, object, null, presence);
            builder.updateMemberCache(member);
        }
        return null;
    }
    getJDA().getGuildSetupController().onMemberChunk(guildId, content);
    return null;
}
Also used : TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) DataArray(net.dv8tion.jda.api.utils.data.DataArray) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) WebSocketClient(net.dv8tion.jda.internal.requests.WebSocketClient) JDAImpl(net.dv8tion.jda.internal.JDAImpl) TLongObjectMap(gnu.trove.map.TLongObjectMap) DataObject(net.dv8tion.jda.api.utils.data.DataObject) MemberImpl(net.dv8tion.jda.internal.entities.MemberImpl) GuildImpl(net.dv8tion.jda.internal.entities.GuildImpl) GuildImpl(net.dv8tion.jda.internal.entities.GuildImpl) DataObject(net.dv8tion.jda.api.utils.data.DataObject) MemberImpl(net.dv8tion.jda.internal.entities.MemberImpl) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Example 47 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class PresenceUpdateHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    // Ignore events for relationships, presences are guild only to us
    if (content.isNull("guild_id")) {
        log.debug("Received PRESENCE_UPDATE without guild_id. Ignoring event.");
        return null;
    }
    if (api.getCacheFlags().stream().noneMatch(CacheFlag::isPresence))
        return null;
    // Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked or not cached.
    final long guildId = content.getUnsignedLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild == null) {
        getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);
        EventCache.LOG.debug("Received a PRESENCE_UPDATE for a guild that is not yet cached! GuildId:{} UserId: {}", guildId, content.getObject("user").get("id"));
        return null;
    }
    CacheView.SimpleCacheView<MemberPresenceImpl> presences = guild.getPresenceView();
    if (presences == null)
        // technically this should be impossible
        return null;
    DataObject jsonUser = content.getObject("user");
    final long userId = jsonUser.getUnsignedLong("id");
    MemberImpl member = (MemberImpl) guild.getMemberById(userId);
    MemberPresenceImpl presence = presences.get(userId);
    OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
    if (status == OnlineStatus.OFFLINE)
        presences.remove(userId);
    if (presence == null) {
        presence = new MemberPresenceImpl();
        if (status != OnlineStatus.OFFLINE) {
            try (UnlockHook lock = presences.writeLock()) {
                presences.getMap().put(userId, presence);
            }
        }
    }
    // Now that we've update the User's info, lets see if we need to set the specific Presence information.
    // This is stored in the Member objects.
    // We set the activities to null to prevent parsing if the cache was disabled
    final DataArray activityArray = !getJDA().isCacheFlagSet(CacheFlag.ACTIVITY) || content.isNull("activities") ? null : content.getArray("activities");
    List<Activity> newActivities = new ArrayList<>();
    boolean parsedActivity = parseActivities(userId, activityArray, newActivities);
    if (getJDA().isCacheFlagSet(CacheFlag.CLIENT_STATUS) && !content.isNull("client_status"))
        handleClientStatus(content, presence);
    // Check if activities changed
    if (parsedActivity)
        handleActivities(newActivities, member, presence);
    if (presence.getOnlineStatus() != status) {
        OnlineStatus oldStatus = presence.getOnlineStatus();
        presence.setOnlineStatus(status);
        if (member != null) {
            getJDA().getEntityBuilder().updateMemberCache(member);
            getJDA().handleEvent(new UserUpdateOnlineStatusEvent(getJDA(), responseNumber, member, oldStatus));
        }
    }
    return null;
}
Also used : CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) MemberImpl(net.dv8tion.jda.internal.entities.MemberImpl) MemberPresenceImpl(net.dv8tion.jda.internal.entities.MemberPresenceImpl) OnlineStatus(net.dv8tion.jda.api.OnlineStatus) ArrayList(java.util.ArrayList) Activity(net.dv8tion.jda.api.entities.Activity) DataArray(net.dv8tion.jda.api.utils.data.DataArray) GuildImpl(net.dv8tion.jda.internal.entities.GuildImpl) DataObject(net.dv8tion.jda.api.utils.data.DataObject) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) UserUpdateOnlineStatusEvent(net.dv8tion.jda.api.events.user.update.UserUpdateOnlineStatusEvent)

Example 48 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class ThreadMembersUpdateHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    long guildId = content.getLong("guild_id");
    if (api.getGuildSetupController().isLocked(guildId))
        return guildId;
    final long threadId = content.getLong("id");
    ThreadChannelImpl thread = (ThreadChannelImpl) getJDA().getThreadChannelById(threadId);
    if (thread == null) {
        getJDA().getEventCache().cache(EventCache.Type.CHANNEL, threadId, responseNumber, allContent, this::handle);
        EventCache.LOG.debug("THREAD_MEMBERS_UPDATE attempted to update a thread that does not exist. JSON: {}", content);
        return null;
    }
    if (!content.isNull("added_members")) {
        DataArray addedMembersJson = content.getArray("added_members");
        handleAddedThreadMembers(thread, addedMembersJson);
    }
    if (!content.isNull("removed_member_ids")) {
        List<Long> removedMemberIds = content.getArray("removed_member_ids").stream(DataArray::getString).map(MiscUtil::parseSnowflake).collect(Collectors.toList());
        handleRemovedThreadMembers(thread, removedMemberIds);
    }
    return null;
}
Also used : ThreadChannelImpl(net.dv8tion.jda.internal.entities.ThreadChannelImpl) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Example 49 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class GuildSetupNode method cleanup.

void cleanup() {
    updateStatus(GuildSetupController.Status.REMOVED);
    EventCache eventCache = getController().getJDA().getEventCache();
    eventCache.clear(EventCache.Type.GUILD, id);
    if (partialGuild == null)
        return;
    Optional<DataArray> channels = partialGuild.optArray("channels");
    Optional<DataArray> roles = partialGuild.optArray("roles");
    channels.ifPresent((arr) -> {
        for (int i = 0; i < arr.length(); i++) {
            DataObject json = arr.getObject(i);
            long id = json.getLong("id");
            eventCache.clear(EventCache.Type.CHANNEL, id);
        }
    });
    roles.ifPresent((arr) -> {
        for (int i = 0; i < arr.length(); i++) {
            DataObject json = arr.getObject(i);
            long id = json.getLong("id");
            eventCache.clear(EventCache.Type.ROLE, id);
        }
    });
    if (members != null) {
        for (TLongObjectIterator<DataObject> it = members.iterator(); it.hasNext(); ) {
            it.advance();
            long userId = it.key();
            if (// if no other setup node contains this userId we clear it here
            !getController().containsMember(userId, this))
                eventCache.clear(EventCache.Type.USER, userId);
        }
    }
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Example 50 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class GuildSetupNode method ensureMembers.

private void ensureMembers() {
    expectedMemberCount = partialGuild.getInt("member_count");
    members = new TLongObjectHashMap<>(expectedMemberCount);
    removedMembers = new TLongHashSet();
    DataArray memberArray = partialGuild.getArray("members");
    if (!getController().getJDA().chunkGuild(id)) {
        handleMemberChunk(true, memberArray);
    } else if (memberArray.length() < expectedMemberCount && !requestedChunk) {
        updateStatus(GuildSetupController.Status.CHUNKING);
        getController().addGuildForChunking(id, isJoin());
        requestedChunk = true;
    } else if (handleMemberChunk(false, memberArray) && !requestedChunk) {
        // Discord sent us enough members to satisfy the member_count
        // but we found duplicates and still didn't reach enough to satisfy the count
        // in this case we try to do chunking instead
        // This is caused by lazy guilds and intended behavior according to jake
        GuildSetupController.log.trace("Received suspicious members with a guild payload. Attempting to chunk. " + "member_count: {} members: {} actual_members: {} guild_id: {}", expectedMemberCount, memberArray.length(), members.size(), id);
        members.clear();
        updateStatus(GuildSetupController.Status.CHUNKING);
        getController().addGuildForChunking(id, isJoin());
        requestedChunk = true;
    }
}
Also used : TLongHashSet(gnu.trove.set.hash.TLongHashSet) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Aggregations

DataArray (net.dv8tion.jda.api.utils.data.DataArray)67 DataObject (net.dv8tion.jda.api.utils.data.DataObject)40 Nonnull (javax.annotation.Nonnull)21 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)14 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)10 JDAImpl (net.dv8tion.jda.internal.JDAImpl)9 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)8 ArrayList (java.util.ArrayList)8 Route (net.dv8tion.jda.internal.requests.Route)8 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)7 Collectors (java.util.stream.Collectors)6 CheckReturnValue (javax.annotation.CheckReturnValue)6 TemplateRole (net.dv8tion.jda.api.entities.templates.TemplateRole)5 ParsingException (net.dv8tion.jda.api.exceptions.ParsingException)5 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)5 Bean (at.xirado.bean.Bean)4 java.util (java.util)4 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)4 Template (net.dv8tion.jda.api.entities.templates.Template)4 CacheView (net.dv8tion.jda.api.utils.cache.CacheView)4