Search in sources :

Example 1 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project Bean by Xirado.

the class GuildDataRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    String authHeader = request.headers("authorization");
    if (authHeader == null || !authHeader.startsWith("Token ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String token = authHeader.substring(7);
    byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
    if (!Bean.getInstance().getAuthenticator().isAuthenticated(tokenBytes)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Invalid token (Try logging out and in again)").toString();
    }
    DataObject user = Bean.getInstance().getAuthenticator().getUser(tokenBytes);
    DataObject body = DataObject.fromJson(request.bodyAsBytes());
    if (body.isNull("guild") || body.isNull("data")) {
        response.status(400);
        return DataObject.empty().put("code", 400).put("message", "Bad request").toString();
    }
    long guildId = Long.parseUnsignedLong(body.getString("guild"));
    long userId = user.getLong("id");
    ShardManager manager = Bean.getInstance().getShardManager();
    Guild guild = manager.getGuildById(guildId);
    if (guild == null) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    Member member;
    try {
        member = guild.retrieveMemberById(userId).complete();
    } catch (ErrorResponseException ex) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", ex.getMessage()).toString();
    }
    if (!member.hasPermission(Permission.ADMINISTRATOR)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    GuildData guildData = GuildManager.getGuildData(guild);
    // Stuff to update
    DataObject updatedData = body.getObject("data");
    // old data
    DataObject currentData = guildData.toData();
    for (String key : updatedData.keys()) {
        if (ALLOWED_SETTINGS.contains(key))
            currentData.put(key, updatedData.get(key));
    }
    guildData.update();
    return user.toString();
}
Also used : GuildData(at.xirado.bean.data.GuildData) DataObject(net.dv8tion.jda.api.utils.data.DataObject) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member)

Example 2 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project Bean by Xirado.

the class GuildsRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    String authHeader = request.headers("authorization");
    if (authHeader == null || !authHeader.startsWith("Token ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String token = authHeader.substring(7);
    byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
    Authenticator authenticator = Bean.getInstance().getAuthenticator();
    if (!authenticator.isAuthenticated(tokenBytes)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Invalid token (Try logging out and in again)").toString();
    }
    if (authenticator.isAccessTokenExpired(tokenBytes))
        authenticator.refreshAccessToken(tokenBytes);
    DataObject object = authenticator.getData(tokenBytes);
    DiscordCredentials credentials = authenticator.getCredentials(tokenBytes);
    String accessToken = credentials.getAccessToken();
    DataObject guilds = WebServer.retrieveGuilds(accessToken);
    if (guilds.isNull("guilds")) {
        DataObject o = DataObject.empty();
        o.put("http_code", guilds.getInt("http_code"));
        if (!guilds.isNull("code"))
            o.put("code", guilds.getInt("code"));
        if (!guilds.isNull("message"))
            o.put("message", guilds.getString("message"));
        return o.toString();
    }
    ShardManager shardManager = Bean.getInstance().getShardManager();
    List<DataObject> adminGuilds = guilds.getArray("guilds").stream(DataArray::getObject).filter(obj -> Permission.getPermissions(obj.getLong("permissions")).contains(Permission.ADMINISTRATOR) || obj.getBoolean("owner")).collect(Collectors.toList());
    DataArray guildArray = DataArray.empty();
    List<DataObject> nonInvitedGuilds = new ArrayList<>();
    for (DataObject guild : adminGuilds) {
        String name = guild.getString("name");
        long id = guild.getLong("id");
        String iconHash = guild.isNull("icon") ? null : guild.getString("icon");
        boolean botJoined = shardManager.getGuildById(id) != null;
        DataObject o = DataObject.empty();
        o.put("name", name);
        o.put("id", id + "");
        if (iconHash != null)
            o.put("icon", DiscordUtils.getIconUrl(id + "", iconHash));
        o.put("bot_joined", botJoined);
        StringBuilder initials = new StringBuilder();
        for (String s : name.split("\\s+")) {
            initials.append(s.charAt(0));
        }
        o.put("initials", initials.toString());
        if (botJoined)
            guildArray.add(o);
        else
            nonInvitedGuilds.add(o);
    }
    guildArray.addAll(nonInvitedGuilds);
    return DataObject.empty().put("guilds", guildArray).put("base_invite_url", InviteURLRoute.getInviteURL()).put("http_code", guilds.getInt("http_code")).toString();
}
Also used : DataArray(net.dv8tion.jda.api.utils.data.DataArray) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) DiscordCredentials(at.xirado.bean.backend.DiscordCredentials) DiscordUtils(at.xirado.bean.backend.DiscordUtils) Authenticator(at.xirado.bean.backend.Authenticator) Permission(net.dv8tion.jda.api.Permission) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) List(java.util.List) WebServer(at.xirado.bean.backend.WebServer) Request(spark.Request) Response(spark.Response) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Route(spark.Route) Bean(at.xirado.bean.Bean) DiscordCredentials(at.xirado.bean.backend.DiscordCredentials) ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) DataArray(net.dv8tion.jda.api.utils.data.DataArray) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Authenticator(at.xirado.bean.backend.Authenticator)

Example 3 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project Bean by Xirado.

the class TokenRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    if (request.headers("authorization") == null) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String authHeader = request.headers("authorization");
    if (!authHeader.startsWith("AuthCode ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String authCode = authHeader.substring(9);
    try {
        DataObject object = DataObject.empty();
        DataObject tokens = Bean.getInstance().getWebServer().retrieveTokens(authCode);
        if (tokens.getInt("status") > 304 || tokens.isNull("access_token")) {
            response.status(400);
            return DataObject.empty().put("code", tokens.isNull("code") ? 400 : tokens.getInt("code")).put("message", tokens.isNull("message") ? "Discord Error" : tokens.getString("message")).toString();
        }
        object.put("tokens", tokens);
        String accessToken = tokens.getString("access_token");
        DataObject userObject = WebServer.retrieveUser(accessToken);
        long id = userObject.getLong("id");
        int discriminator = Integer.parseInt(userObject.getString("discriminator"));
        String effectiveAvatarURL = "";
        if (userObject.isNull("avatar"))
            effectiveAvatarURL = "https://cdn.discordapp.com/embed/avatars/" + (discriminator % 5) + ".png";
        else {
            String avatarHash = userObject.getString("avatar");
            boolean animated = avatarHash.startsWith("a_");
            effectiveAvatarURL = "https://cdn.discordapp.com/avatars/" + id + "/" + avatarHash + (animated ? ".gif" : ".png");
        }
        userObject.put("effective_avatar", effectiveAvatarURL);
        object.put("user", userObject);
        byte[] tokenBytes = Bean.getInstance().getAuthenticator().addSession(object);
        String token = new String(tokenBytes, StandardCharsets.UTF_8);
        response.header("authorization", "Token " + token);
        return userObject.toString();
    } catch (Exception ex) {
        response.status(500);
        return DataObject.empty().put("code", 500).put("message", "Internal Server Error").toString();
    }
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject)

Example 4 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project Bean by Xirado.

the class UserRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    String authHeader = request.headers("authorization");
    if (authHeader == null || !authHeader.startsWith("Token ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String token = authHeader.substring(7);
    byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
    Authenticator authenticator = Bean.getInstance().getAuthenticator();
    if (!authenticator.isAuthenticated(tokenBytes)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Invalid token (Try logging out and in again)").toString();
    }
    if (authenticator.isAccessTokenExpired(tokenBytes))
        authenticator.refreshAccessToken(tokenBytes);
    DataObject user = authenticator.getData(tokenBytes);
    long id = user.getObject("user").getLong("id");
    int discriminator = Integer.parseInt(user.getObject("user").getString("discriminator"));
    String effectiveAvatarURL = "";
    if (user.getObject("user").isNull("avatar"))
        effectiveAvatarURL = "https://cdn.discordapp.com/embed/avatars/" + (discriminator % 5) + ".png";
    else {
        String avatarHash = user.getObject("user").getString("avatar");
        boolean animated = avatarHash.startsWith("a_");
        effectiveAvatarURL = "https://cdn.discordapp.com/avatars/" + id + "/" + avatarHash + (animated ? ".gif" : ".png");
    }
    user.getObject("user").put("effective_avatar", effectiveAvatarURL);
    return user.toString();
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) Authenticator(at.xirado.bean.backend.Authenticator)

Example 5 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project Bean by Xirado.

the class Authenticator method refreshAccessToken.

public void refreshAccessToken(byte[] token) throws IOException {
    if (!isAuthenticated(token))
        throw new IllegalStateException("User unauthenticated!");
    DiscordCredentials credentials = getCredentials(token);
    if (!isAccessTokenExpired((token)))
        return;
    DiscordCredentials newCredentials = credentials.refreshToken();
    DataObject tokens = DataObject.empty().put("access_token", newCredentials.getAccessToken()).put("refresh_token", newCredentials.getRefreshToken()).put("scope", String.join(" ", newCredentials.getScopes())).put("token_type", newCredentials.getTokenType()).put("expires_in", newCredentials.getExpiresIn());
    DataObject data = getData(token);
    data.put("discord_timestamp", System.currentTimeMillis() / 1000).put("tokens", tokens);
    users.put(ByteBuffer.wrap(token), data);
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject)

Aggregations

DataObject (net.dv8tion.jda.api.utils.data.DataObject)155 Nonnull (javax.annotation.Nonnull)43 DataArray (net.dv8tion.jda.api.utils.data.DataArray)43 Route (net.dv8tion.jda.internal.requests.Route)12 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)11 JDAImpl (net.dv8tion.jda.internal.JDAImpl)11 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)11 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)10 Guild (net.dv8tion.jda.api.entities.Guild)9 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)9 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)9 UnlockHook (net.dv8tion.jda.internal.utils.UnlockHook)9 OffsetDateTime (java.time.OffsetDateTime)8 Collectors (java.util.stream.Collectors)8 ArrayList (java.util.ArrayList)7 CacheView (net.dv8tion.jda.api.utils.cache.CacheView)7 java.util (java.util)6 Nullable (javax.annotation.Nullable)6 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)5 TLongObjectMap (gnu.trove.map.TLongObjectMap)4