Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement thread member pagination #2338

Merged
merged 4 commits into from
Nov 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import net.dv8tion.jda.api.managers.channel.concrete.ThreadChannelManager;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.CacheRestAction;
import net.dv8tion.jda.api.requests.restaction.pagination.ThreadMemberPaginationAction;
import net.dv8tion.jda.api.utils.MiscUtil;
import net.dv8tion.jda.internal.utils.Checks;

Expand Down Expand Up @@ -442,13 +443,14 @@ default CacheRestAction<ThreadMember> retrieveThreadMemberById(@Nonnull String i
/**
* Retrieves the {@link ThreadMember ThreadMembers} of this thread.
*
* <p>This requires the {@link net.dv8tion.jda.api.requests.GatewayIntent#GUILD_MEMBERS} intent to be enabled.
* <p>This requires the {@link net.dv8tion.jda.api.requests.GatewayIntent#GUILD_MEMBERS} intent to be enabled
* in the <a href="https://discord.com/developers/applications" target="_blank">Application Dashboard</a>.
*
* @return a RestAction that resolves into a List of {@link ThreadMember ThreadMembers} of this thread.
* @return {@link ThreadMemberPaginationAction}
*/
//TODO-v5: docs - documentation depends on implementation cleanup.
@Nonnull
@CheckReturnValue
RestAction<List<ThreadMember>> retrieveThreadMembers();
ThreadMemberPaginationAction retrieveThreadMembers();

/**
* Whether the current account is the owner of this thread.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.dv8tion.jda.api.requests.restaction.pagination;

import net.dv8tion.jda.api.entities.ThreadMember;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;

import javax.annotation.Nonnull;

/**
* {@link PaginationAction} that paginates the thread members endpoint.
* <br>Note that this implementation is not considered thread-safe as modifications to the cache are not done
* with a lock. Calling methods on this class from multiple threads is not recommended.
*
* <p><b>Must provide not-null {@link ThreadChannel} to compile a valid
* pagination route.</b>
*
* <p><b>Limits:</b><br>
* Minimum - 1
* <br>Maximum - 100
*
* <p><b>Example</b><br>
* <pre>{@code
* // Count all thread members who are bots
* public static CompletableFuture<AtomicInteger> countBotMembers(ThreadChannel thread) {
* AtomicInteger count = new AtomicInteger();
* ThreadMemberPaginationAction members = thread.retrieveThreadMembers();
* return members.forEachAsync((threadMember) -> {
* if (threadMember.getUser().isBot())
* count.incrementAndGet();
* return true; // continues iterating if this returns true
* }).thenApply((v) -> count);
* }
* }</pre>
*
* @see ThreadChannel#retrieveThreadMembers()
*/
public interface ThreadMemberPaginationAction extends PaginationAction<ThreadMember, ThreadMemberPaginationAction>
{
/**
* The {@link ThreadChannel} this action fetches members for.
*
* @return The channel
*/
@Nonnull
ThreadChannel getThreadChannel();
}
27 changes: 27 additions & 0 deletions src/main/java/net/dv8tion/jda/api/utils/data/DataObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,33 @@ else if (value instanceof SerializableArray)
return this;
}

/**
* Renames an existing field to the new name.
* <br>This is a shorthand to {@link #remove(String) remove} under the old key and then {@link #put(String, Object) put} under the new key.
*
* <p>If there is nothing mapped to the old key, this does nothing.
*
* @param key
* The old key
* @param newKey
* The new key
*
* @throws IllegalArgumentException
* If null is provided
*
* @return A DataObject with the updated value
*/
@Nonnull
public DataObject rename(@Nonnull String key, @Nonnull String newKey)
{
Checks.notNull(key, "Key");
Checks.notNull(newKey, "Key");
if (!this.data.containsKey(key))
return this;
this.data.put(newKey, this.data.remove(key));
return this;
}

/**
* {@link java.util.Collection} of all values in this DataObject.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,10 @@
import net.dv8tion.jda.api.managers.channel.concrete.ThreadChannelManager;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.CacheRestAction;
import net.dv8tion.jda.api.requests.restaction.pagination.ThreadMemberPaginationAction;
import net.dv8tion.jda.api.utils.TimeUtil;
import net.dv8tion.jda.api.utils.cache.CacheView;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.entities.EntityBuilder;
import net.dv8tion.jda.internal.entities.GuildImpl;
import net.dv8tion.jda.internal.entities.channel.middleman.AbstractGuildChannelImpl;
import net.dv8tion.jda.internal.entities.channel.mixin.attribute.ISlowmodeChannelMixin;
Expand All @@ -47,6 +45,7 @@
import net.dv8tion.jda.internal.requests.DeferredRestAction;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.requests.Route;
import net.dv8tion.jda.internal.requests.restaction.pagination.ThreadMemberPaginationActionImpl;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.Helpers;

Expand All @@ -55,7 +54,6 @@
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

Expand Down Expand Up @@ -204,33 +202,17 @@ public CacheRestAction<ThreadMember> retrieveThreadMemberById(long id)
return new DeferredRestAction<>(jda, ThreadMember.class,
() -> getThreadMemberById(id),
() -> {
Route.CompiledRoute route = Route.Channels.GET_THREAD_MEMBER.compile(getId(), Long.toUnsignedString(id));
Route.CompiledRoute route = Route.Channels.GET_THREAD_MEMBER.compile(getId(), Long.toUnsignedString(id)).withQueryParams("with_member", "true");
return new RestActionImpl<>(jda, route, (resp, req) ->
jda.getEntityBuilder().createThreadMember(getGuild(), this, resp.getObject()));
jda.getEntityBuilder().createThreadMember(getGuild(), this, resp.getObject().rename("guild_member", "member")));
});
}

@Nonnull
@Override
public RestAction<List<ThreadMember>> retrieveThreadMembers()
{
//TODO-threads: This interacts with GUILD_MEMBERS in some way. Need to test and document how.

Route.CompiledRoute route = Route.Channels.LIST_THREAD_MEMBERS.compile(getId());
return new RestActionImpl<>(getJDA(), route, (response, request) ->
{
EntityBuilder builder = api.getEntityBuilder();
List<ThreadMember> threadMembers = new LinkedList<>();
DataArray memberArr = response.getArray();

for (int i = 0; i < memberArr.length(); i++)
{
final DataObject object = memberArr.getObject(i);
//Very possible this is gonna break because we don't get user/member info with threadmembers
//TODO revisit the @Nonnull annotations in ThreadMember due to the lack of user/member info. Might be a time to introduce RestX entities?
threadMembers.add(builder.createThreadMember((GuildImpl) this.getGuild(), this, object));
}
return Collections.unmodifiableList(threadMembers);
});
public ThreadMemberPaginationAction retrieveThreadMembers()
{
return new ThreadMemberPaginationActionImpl(this);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.entities.EntityBuilder;
import net.dv8tion.jda.internal.entities.GuildImpl;
import net.dv8tion.jda.internal.entities.channel.concrete.ThreadChannelImpl;
import net.dv8tion.jda.internal.utils.UnlockHook;

Expand Down Expand Up @@ -85,7 +84,7 @@ private void handleAddedThreadMembers(ThreadChannelImpl thread, DataArray addedM
for (int i = 0; i < addedMembersJson.length(); i++)
{
DataObject threadMemberJson = addedMembersJson.getObject(i);
ThreadMember threadMember = entityBuilder.createThreadMember((GuildImpl) thread.getGuild(), thread, threadMemberJson);
ThreadMember threadMember = entityBuilder.createThreadMember(thread.getGuild(), thread, threadMemberJson);
addedThreadMembers.add(threadMember);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.dv8tion.jda.internal.requests.restaction.pagination;

import net.dv8tion.jda.api.entities.ThreadMember;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
import net.dv8tion.jda.api.exceptions.ParsingException;
import net.dv8tion.jda.api.requests.Request;
import net.dv8tion.jda.api.requests.Response;
import net.dv8tion.jda.api.requests.restaction.pagination.ThreadMemberPaginationAction;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.internal.entities.EntityBuilder;
import net.dv8tion.jda.internal.entities.channel.concrete.ThreadChannelImpl;
import net.dv8tion.jda.internal.requests.Route;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class ThreadMemberPaginationActionImpl
extends PaginationActionImpl<ThreadMember, ThreadMemberPaginationAction>
implements ThreadMemberPaginationAction
{
private final ThreadChannelImpl channel;

public ThreadMemberPaginationActionImpl(ThreadChannel channel)
{
super(channel.getJDA(), Route.Channels.LIST_THREAD_MEMBERS.compile(channel.getId()).withQueryParams("with_member", "true"), 1, 100, 100);
this.channel = (ThreadChannelImpl) channel;
this.order = PaginationOrder.FORWARD;
}

@Nonnull
@Override
public ThreadChannel getThreadChannel()
{
return channel;
}

@Nonnull
@Override
public EnumSet<PaginationOrder> getSupportedOrders()
{
return EnumSet.of(getOrder());
}

@Override
protected long getKey(ThreadMember it)
{
return it.getIdLong();
}

@Override
protected void handleSuccess(Response response, Request<List<ThreadMember>> request)
{
DataArray array = response.getArray();
List<ThreadMember> members = new ArrayList<>(array.length());
EntityBuilder builder = api.getEntityBuilder();
for (int i = 0; i < array.length(); i++)
{
try
{
DataObject object = array.getObject(i);
if (object.isNull("guild_member"))
continue;
object.rename("guild_member", "member");
ThreadMember threadMember = builder.createThreadMember(channel.getGuild(), channel, object);
members.add(threadMember);
}
catch (ParsingException | NullPointerException e)
{
LOG.warn("Encountered an exception in ThreadMemberPaginationAction", e);
}
}

// if (order == PaginationOrder.BACKWARD)
// Collections.reverse(members);
if (useCache)
cached.addAll(members);

if (!members.isEmpty())
{
last = members.get(members.size() - 1);
lastKey = last.getIdLong();
}
request.onSuccess(members);
}
}