Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/main/java/com/seailz/discordjv/DiscordJv.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.seailz.discordjv.utils.Checker;
import com.seailz.discordjv.utils.URLS;
import com.seailz.discordjv.utils.cache.Cache;
import com.seailz.discordjv.utils.cache.JsonCache;
import com.seailz.discordjv.utils.discordapi.DiscordRequest;
import com.seailz.discordjv.utils.discordapi.DiscordResponse;
import com.seailz.discordjv.utils.discordapi.RateLimit;
Expand Down Expand Up @@ -101,6 +102,10 @@ public class DiscordJv {
* The command dispatcher
*/
protected final CommandDispatcher commandDispatcher;
/**
* A cache storing self user information
*/
private JsonCache selfUserCache;

/**
* Creates a new instance of the DiscordJv class
Expand Down Expand Up @@ -374,11 +379,20 @@ public Cache<Guild> getGuildCache() {
*/
@Nullable
public Application getSelfInfo() {
DiscordResponse response = new DiscordRequest(
if (this.selfUserCache != null && !selfUserCache.isEmpty())
return Application.decompile(selfUserCache.get(), this);

DiscordRequest request = new DiscordRequest(
new JSONObject(), new HashMap<>(),
URLS.GET.APPLICATION.APPLICATION_INFORMATION,
this, URLS.GET.APPLICATION.APPLICATION_INFORMATION, RequestMethod.GET
).invoke();
);
DiscordResponse response = request.invoke();

if (this.selfUserCache == null)
this.selfUserCache = JsonCache.newc(response.body(), request);
this.selfUserCache.update(response.body());

return Application.decompile(response.body(), this);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message)
heartbeatCycle.sendHeartbeat();
break;
case DISPATCHED:
System.out.println(message.getPayload());
handleDispatched(payload);
break;
case RECONNECT:
Expand Down
73 changes: 67 additions & 6 deletions src/main/java/com/seailz/discordjv/model/guild/Guild.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
import com.seailz.discordjv.model.guild.welcome.WelcomeScreen;
import com.seailz.discordjv.model.role.Role;
import com.seailz.discordjv.model.user.User;
import com.seailz.discordjv.utils.Checker;
import com.seailz.discordjv.utils.URLS;
import com.seailz.discordjv.utils.cache.JsonCache;
import com.seailz.discordjv.utils.discordapi.DiscordRequest;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -112,7 +114,8 @@ public record Guild(
WelcomeScreen welcomeScreen,
List<Sticker> stickers,
boolean premiumProgressBarEnabled,
DiscordJv discordJv
DiscordJv discordJv,
JsonCache roleCache
) implements Compilerable {


Expand Down Expand Up @@ -432,7 +435,7 @@ public static Guild decompile(JSONObject obj, DiscordJv discordJv) {
premiumProgressBarEnabled = false;
}

return new Guild(
Guild g = new Guild(
id,
name,
icon,
Expand Down Expand Up @@ -470,8 +473,18 @@ public static Guild decompile(JSONObject obj, DiscordJv discordJv) {
welcomeScreen,
stickers,
premiumProgressBarEnabled,
discordJv
discordJv,
JsonCache.newc(new DiscordRequest(
new JSONObject(),
new HashMap<>(),
URLS.GET.GUILDS.ROLES.GET_GUILD_ROLES.replace("{guild.id}", id),
discordJv,
URLS.GET.GUILDS.ROLES.GET_GUILD_ROLES,
RequestMethod.GET
))
);
g.roleCache.reset(60000);
return g;
}

/**
Expand Down Expand Up @@ -656,6 +669,31 @@ public Member getMemberById(String id) {
);
}

public List<Member> getMembers(int limit, String after) {
Checker.check(limit <= 0, "Limit must be greater than 0");
Checker.check(limit > 1000, "Limit must be less than or equal to 1000");
JSONArray arr = new DiscordRequest(
new JSONObject(),
new HashMap<>(),
URLS.GET.GUILDS.MEMBERS.LIST_GUILD_MEMBERS.replace(
"{guild.id}",
id
) + "?limit=" + limit + (after == null ? "" : "&after=" + after),
discordJv,
URLS.GET.GUILDS.MEMBERS.LIST_GUILD_MEMBERS,
RequestMethod.GET
).invoke().arr();

List<Member> members = new ArrayList<>();
for (Object obj : arr) {
members.add(Member.decompile((JSONObject) obj, discordJv, id, this));
}
System.out.println(arr);

return members;
}


public List<Member> getMembers() {
JSONArray arr = new DiscordRequest(
new JSONObject(),
Expand All @@ -670,7 +708,11 @@ public List<Member> getMembers() {
).invoke().arr();

List<Member> members = new ArrayList<>();
arr.forEach(o -> members.add(Member.decompile((JSONObject) o, discordJv, id, this)));
for (Object obj : arr) {
members.add(Member.decompile((JSONObject) obj, discordJv, id, this));
}
System.out.println(arr);

return members;
}

Expand Down Expand Up @@ -740,17 +782,36 @@ public List<GuildChannel> getChannels() {
return channels;
}

/**
* Retrieves all the roles of a guild.
* This method uses caching, the cache will reset every 1 minute.
*
* @return
*/
public List<Role> roles() {
if (roleCache != null && !roleCache.isEmpty()) {
List<Role> roles = new ArrayList<>();
roleCache.get().getJSONArray("data").forEach(
o -> roles.add(Role.decompile((JSONObject) o))
);
return roles;
}

List<Role> roles = new ArrayList<>();
JSONArray res = new DiscordRequest(
DiscordRequest req = new DiscordRequest(
new JSONObject(),
new HashMap<>(),
URLS.GET.GUILDS.ROLES.GET_GUILD_ROLES.replace("{guild.id}", id),
discordJv,
URLS.GET.GUILDS.ROLES.GET_GUILD_ROLES,
RequestMethod.GET
).invoke().arr();
);
JSONArray res = req.invoke().arr();
res.forEach(o -> roles.add(Role.decompile((JSONObject) o)));

if (roleCache != null) {
roleCache.update(new JSONObject().put("data", res));
}
return roles;
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/seailz/discordjv/model/guild/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ public static Member decompile(JSONObject obj, DiscordJv discordJv, String guild
List<Permission> permissions = null;
String communicationDisabledUntil;

System.out.println(obj);

try {
user = User.decompile(obj.getJSONObject("user"), discordJv);
Expand All @@ -106,8 +105,9 @@ public static Member decompile(JSONObject obj, DiscordJv discordJv, String guild
if (obj.has("roles")) {
if (guild != null) {
List<Role> rolesList = new ArrayList<>();
List<Role> guildRoles = guild.roles();
for (Object o : obj.getJSONArray("roles")) {
guild.roles().stream()
guildRoles.stream()
.filter(role -> role.id().equals(o.toString()))
.findFirst()
.ifPresent(rolesList::add);
Expand Down Expand Up @@ -186,7 +186,7 @@ public void timeout(int seconds) {
URLS.PATCH.GUILD.MEMBER.MODIFY_GUILD_MEMBER,
RequestMethod.PATCH
).invoke();
System.out.println(timeout);

}

public void removeTimeout() {
Expand Down
127 changes: 127 additions & 0 deletions src/main/java/com/seailz/discordjv/utils/cache/JsonCache.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package com.seailz.discordjv.utils.cache;

import com.seailz.discordjv.DiscordJv;
import com.seailz.discordjv.utils.cache.impl.JsonCacheImpl;
import com.seailz.discordjv.utils.discordapi.DiscordRequest;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.Random;

/**
* A cache that can be used to store JSON objects.
* <p>
* This cache is used to store JSON objects that are retrieved from the Discord API,
* <br>and is used in places where unnecessary requests to the Discord API would be made.
* <p>
* This cache is not persistent, and will be cleared when the bot is restarted.
* <br>This cache is not thread-safe.
*
* @author Seailz
*/
public interface JsonCache {

/**
* Returns the JSON object stored in the cache,
* <br>or null if the cache is empty.
*/
@Nullable
JSONObject get();

/**
* Updates the cache.
*
* @param object The object to update the cache with
*/
void update(JSONObject object);

/**
* Returns the DiscordRequest object that
* <br>is used to retrieve a fresh copy of the
* <br>data stored by this cache.
* <p>
* Used by {@link #updateFresh()} to retrieve
* <br>the latest data.
* <p>
* The {@link DiscordRequest} object that is returned
* <br>is provided by the {@link DiscordJv} instance (or another internal class).
*
* @return {@link DiscordRequest} object that can be invoked to return the latest
* data relevant to this cache.
*/
DiscordRequest howToUpdateFresh();

/**
* Given an interval, this method starts
* <br>a repeating timer on that interval that
* <br>will clear the cache.
* <p>
* This is to be used if it is harder
* <br>to update the cache and a better
* <br>option to just set up a repeating clear.
*
* @param interval The interval on which to invalidate the cache.
*/
default void reset(int interval) {
new Thread(() -> {
while (true) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
invalidate();
}
}, "CacheInvalidate" + new Random().nextInt(999)).start();
}

/**
* Updates the cached object.
* <p>
* This will update the object by using the Discord API,
* to request a new version of the object.
* <p>
* This method should not be used very often, and is
* <br>just here in case it is needed in the future by the library,
* <br>or if a developer using the library wants to use it.
*
* @see #howToUpdateFresh()
*/
default void updateFresh() {
if (howToUpdateFresh() == null) return;
update(howToUpdateFresh().invoke().body());
}

/**
* Invalidates the cache.
* Literally just sets the cached object to null.
*/
default void invalidate() {
update(null);
}

/**
* Returns true if the cache is empty or false if it is not.
*/
default boolean isEmpty() {
return get() == null;
}


/**
* Returns a new, empty JsonCache object.
*/
static JsonCache newc(DiscordRequest howToUpdateFresh) {
return new JsonCacheImpl(howToUpdateFresh);
}

/**
* Returns a new JsonCache object with the specified object.
*
* @param object The object to store in the cache when initialized.
*/
static JsonCache newc(JSONObject object, DiscordRequest howToUpdateFresh) {
return new JsonCacheImpl(object, howToUpdateFresh);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.seailz.discordjv.utils.cache.impl;

import com.seailz.discordjv.utils.cache.JsonCache;
import com.seailz.discordjv.utils.discordapi.DiscordRequest;
import org.json.JSONObject;

/**
* Implementation of the {@link JsonCache} interface.
*
* @author Seailz
*/
public class JsonCacheImpl implements JsonCache {

private JSONObject object;
private final DiscordRequest request;

/**
* Creates a new JsonCacheImpl object.
*
* @param object The object to store in the cache
*/
public JsonCacheImpl(JSONObject object, DiscordRequest request) {
this.object = object;
this.request = request;
}

/**
* Creates an empty JsonCacheImpl object.
*/
public JsonCacheImpl(DiscordRequest request) {
this.object = null;
this.request = request;
}

@Override
public JSONObject get() {
return object;
}

@Override
public void update(JSONObject object) {
this.object = object;
}

@Override
public DiscordRequest howToUpdateFresh() {
return request;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ else if (requestMethod == RequestMethod.DELETE) {
return null;
}

System.out.println(body);

JSONObject error = new JSONObject(response.body());
JSONArray errorArray;
Expand Down