Search in sources :

Example 1 with DiscordApiImpl

use of org.javacord.core.DiscordApiImpl in project Javacord by BtoBastian.

the class MessageBuilderBaseDelegateImpl method checkForAttachmentsAndExecuteRequest.

// //////////////////////////////////////////////////////////////////////////////
// Internal MessageBuilder utility methods
// //////////////////////////////////////////////////////////////////////////////
private CompletableFuture<Message> checkForAttachmentsAndExecuteRequest(TextChannel channel, ObjectNode body, RestRequest<Message> request, boolean clearAttachmentsIfAppropriate) {
    if (attachments.isEmpty() && embeds.stream().noneMatch(EmbedBuilder::requiresAttachments)) {
        if (clearAttachmentsIfAppropriate) {
            body.set("attachments", JsonNodeFactory.instance.objectNode().arrayNode());
        }
        return executeRequestWithoutAttachments(channel, body, request);
    }
    CompletableFuture<Message> future = new CompletableFuture<>();
    // We access files etc. so this should be async
    channel.getApi().getThreadPool().getExecutorService().submit(() -> {
        try {
            List<FileContainer> tempAttachments = new ArrayList<>(attachments);
            // Add the attachments required for the embeds
            for (EmbedBuilder embed : embeds) {
                tempAttachments.addAll(((EmbedBuilderDelegateImpl) embed.getDelegate()).getRequiredAttachments());
            }
            addMultipartBodyToRequest(request, body, tempAttachments, channel.getApi());
            request.execute(result -> ((DiscordApiImpl) channel.getApi()).getOrCreateMessage(channel, result.getJsonBody())).whenComplete((newMessage, throwable) -> {
                if (throwable != null) {
                    future.completeExceptionally(throwable);
                } else {
                    future.complete(newMessage);
                }
            });
        } catch (Throwable t) {
            future.completeExceptionally(t);
        }
    });
    return future;
}
Also used : MessageAttachment(org.javacord.api.entity.message.MessageAttachment) Arrays(java.util.Arrays) Member(org.javacord.core.entity.user.Member) URL(java.net.URL) RestMethod(org.javacord.core.util.rest.RestMethod) FileContainer(org.javacord.core.util.FileContainer) HighLevelComponent(org.javacord.api.entity.message.component.HighLevelComponent) RestRequest(org.javacord.core.util.rest.RestRequest) EmbedBuilderDelegateImpl(org.javacord.core.entity.message.embed.EmbedBuilderDelegateImpl) JsonNode(com.fasterxml.jackson.databind.JsonNode) ComponentType(org.javacord.api.entity.message.component.ComponentType) MediaType(okhttp3.MediaType) ActionRowBuilder(org.javacord.api.entity.message.component.ActionRowBuilder) MessageBuilderBaseDelegate(org.javacord.api.entity.message.internal.MessageBuilderBaseDelegate) BufferedImage(java.awt.image.BufferedImage) Messageable(org.javacord.api.entity.message.Messageable) Collection(java.util.Collection) Set(java.util.Set) EmbedBuilder(org.javacord.api.entity.message.embed.EmbedBuilder) AllowedMentions(org.javacord.api.entity.message.mention.AllowedMentions) Message(org.javacord.api.entity.message.Message) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MultipartBody(okhttp3.MultipartBody) Mentionable(org.javacord.api.entity.Mentionable) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) AllowedMentionsImpl(org.javacord.core.entity.message.mention.AllowedMentionsImpl) CompletableFuture(java.util.concurrent.CompletableFuture) ComponentImpl(org.javacord.core.entity.message.component.ComponentImpl) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) IncomingWebhook(org.javacord.api.entity.webhook.IncomingWebhook) RequestBody(okhttp3.RequestBody) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MessageDecoration(org.javacord.api.entity.message.MessageDecoration) URLConnection(java.net.URLConnection) Icon(org.javacord.api.entity.Icon) TextChannel(org.javacord.api.entity.channel.TextChannel) DiscordApiImpl(org.javacord.core.DiscordApiImpl) ActionRow(org.javacord.api.entity.message.component.ActionRow) LowLevelComponent(org.javacord.api.entity.message.component.LowLevelComponent) File(java.io.File) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) User(org.javacord.api.entity.user.User) DiscordApi(org.javacord.api.DiscordApi) Collections(java.util.Collections) InputStream(java.io.InputStream) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(org.javacord.api.entity.message.embed.EmbedBuilder) Message(org.javacord.api.entity.message.Message) DiscordApiImpl(org.javacord.core.DiscordApiImpl) ArrayList(java.util.ArrayList) FileContainer(org.javacord.core.util.FileContainer)

Example 2 with DiscordApiImpl

use of org.javacord.core.DiscordApiImpl in project Javacord by BtoBastian.

the class CustomEmojiBuilderDelegateImpl method create.

@Override
public CompletableFuture<KnownCustomEmoji> create() {
    if (name == null) {
        throw new IllegalStateException("The name is no optional parameter!");
    }
    if (image == null) {
        throw new IllegalStateException("The image is no optional parameter!");
    }
    ObjectNode body = JsonNodeFactory.instance.objectNode().put("name", name);
    if (whitelist != null) {
        ArrayNode jsonRoles = body.putArray("roles");
        whitelist.stream().map(Role::getIdAsString).forEach(jsonRoles::add);
    }
    return image.asByteArray(server.getApi()).thenAccept(bytes -> {
        String base64Icon = "data:image/" + image.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
        body.put("image", base64Icon);
    }).thenCompose(aVoid -> new RestRequest<KnownCustomEmoji>(server.getApi(), RestMethod.POST, RestEndpoint.CUSTOM_EMOJI).setUrlParameters(server.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> ((DiscordApiImpl) server.getApi()).getOrCreateKnownCustomEmoji(server, result.getJsonBody())));
}
Also used : ServerImpl(org.javacord.core.entity.server.ServerImpl) KnownCustomEmoji(org.javacord.api.entity.emoji.KnownCustomEmoji) CustomEmojiBuilderDelegate(org.javacord.api.entity.emoji.internal.CustomEmojiBuilderDelegate) Arrays(java.util.Arrays) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) Collection(java.util.Collection) CompletableFuture(java.util.concurrent.CompletableFuture) DiscordApiImpl(org.javacord.core.DiscordApiImpl) RestMethod(org.javacord.core.util.rest.RestMethod) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FileContainer(org.javacord.core.util.FileContainer) File(java.io.File) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) HashSet(java.util.HashSet) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Base64(java.util.Base64) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Role(org.javacord.api.entity.permission.Role) Icon(org.javacord.api.entity.Icon) RestRequest(org.javacord.core.util.rest.RestRequest) InputStream(java.io.InputStream) KnownCustomEmoji(org.javacord.api.entity.emoji.KnownCustomEmoji) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DiscordApiImpl(org.javacord.core.DiscordApiImpl) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 3 with DiscordApiImpl

use of org.javacord.core.DiscordApiImpl in project Javacord by BtoBastian.

the class ServerUpdaterDelegateImpl method update.

@Override
public CompletableFuture<Void> update() {
    // A set with all members that get updates
    HashSet<User> members = new HashSet<>(userRoles.keySet());
    members.addAll(userNicknames.keySet());
    members.addAll(userMuted.keySet());
    members.addAll(userDeafened.keySet());
    members.addAll(userMoveTargets.keySet());
    // A list with all tasks
    List<CompletableFuture<?>> tasks = new ArrayList<>();
    members.forEach(member -> {
        boolean patchMember = false;
        ObjectNode updateNode = JsonNodeFactory.instance.objectNode();
        Collection<Role> roles = userRoles.get(member);
        if (roles != null) {
            ArrayNode rolesJson = updateNode.putArray("roles");
            roles.stream().map(DiscordEntity::getIdAsString).forEach(rolesJson::add);
            patchMember = true;
        }
        if (userNicknames.containsKey(member)) {
            String nickname = userNicknames.get(member);
            if (member.isYourself()) {
                tasks.add(new RestRequest<Void>(server.getApi(), RestMethod.PATCH, RestEndpoint.OWN_NICKNAME).setUrlParameters(server.getIdAsString()).setBody(JsonNodeFactory.instance.objectNode().put("nick", nickname)).setAuditLogReason(reason).execute(result -> null));
            } else {
                updateNode.put("nick", (nickname == null) ? "" : nickname);
                patchMember = true;
            }
        }
        if (userMuted.containsKey(member)) {
            updateNode.put("mute", userMuted.get(member));
            patchMember = true;
        }
        if (userDeafened.containsKey(member)) {
            updateNode.put("deaf", userDeafened.get(member));
            patchMember = true;
        }
        if (userMoveTargets.containsKey(member)) {
            ServerVoiceChannel channel = userMoveTargets.get(member);
            if (member.isYourself()) {
                ((DiscordApiImpl) server.getApi()).getWebSocketAdapter().sendVoiceStateUpdate(server, channel, null, null);
            } else if (channel != null) {
                updateNode.put("channel_id", channel.getId());
                patchMember = true;
            } else {
                updateNode.putNull("channel_id");
                patchMember = true;
            }
        }
        if (patchMember) {
            tasks.add(new RestRequest<Void>(server.getApi(), RestMethod.PATCH, RestEndpoint.SERVER_MEMBER).setUrlParameters(server.getIdAsString(), member.getIdAsString()).setBody(updateNode).setAuditLogReason(reason).execute(result -> null));
        }
    });
    if (newRolesOrder != null) {
        tasks.add(server.reorderRoles(newRolesOrder, reason));
    }
    // Server settings
    boolean patchServer = false;
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (name != null) {
        body.put("name", name);
        patchServer = true;
    }
    if (region != null) {
        body.put("region", region.getKey());
        patchServer = true;
    }
    if (explicitContentFilterLevel != null) {
        body.put("explicit_content_filter", explicitContentFilterLevel.getId());
        patchServer = true;
    }
    if (verificationLevel != null) {
        body.put("verification_level", verificationLevel.getId());
        patchServer = true;
    }
    if (defaultMessageNotificationLevel != null) {
        body.put("default_message_notifications", defaultMessageNotificationLevel.getId());
        patchServer = true;
    }
    if (updateAfkChannel) {
        if (afkChannel != null) {
            body.put("afk_channel_id", afkChannel.getIdAsString());
        } else {
            body.putNull("afk_channel_id");
        }
        patchServer = true;
    }
    if (afkTimeout != null) {
        body.put("afk_timeout", afkTimeout.intValue());
        patchServer = true;
    }
    if (updateIcon) {
        if (icon == null) {
            body.putNull("icon");
        }
        patchServer = true;
    }
    if (updateSplash) {
        if (splash == null) {
            body.putNull("splash");
        }
        patchServer = true;
    }
    if (owner != null) {
        body.put("owner_id", owner.getIdAsString());
        patchServer = true;
    }
    if (updateSystemChannel) {
        if (systemChannel != null) {
            body.put("system_channel_id", systemChannel.getIdAsString());
        } else {
            body.putNull("system_channel_id");
        }
        patchServer = true;
    }
    if (updateModeratorsOnlyChannel) {
        if (moderatorsOnlyChannel != null) {
            body.put("public_updates_channel_id", moderatorsOnlyChannel.getIdAsString());
        } else {
            body.putNull("public_updates_channel_id");
        }
        patchServer = true;
    }
    if (updateRulesChannel) {
        if (rulesChannel != null) {
            body.put("rules_channel_id", rulesChannel.getIdAsString());
        } else {
            body.putNull("rules_channel_id");
        }
        patchServer = true;
    }
    if (updateBanner) {
        if (banner == null) {
            body.putNull("banner");
        }
        patchServer = true;
    }
    if (updateLocale) {
        if (locale == null) {
            body.putNull("preferred_locale");
        } else {
            body.put("preferred_locale", locale.toLanguageTag());
        }
        patchServer = true;
    }
    // Only make a REST call, if we really want to update something
    if (patchServer) {
        if (icon != null || splash != null || banner != null) {
            CompletableFuture<Void> iconFuture = null;
            if (icon != null) {
                iconFuture = icon.asByteArray(server.getApi()).thenAccept(bytes -> {
                    String base64Icon = "data:image/" + icon.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
                    body.put("icon", base64Icon);
                });
            }
            CompletableFuture<Void> splashFuture = null;
            if (splash != null) {
                splashFuture = splash.asByteArray(server.getApi()).thenAccept(bytes -> {
                    String base64Splash = "data:image/" + splash.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
                    body.put("splash", base64Splash);
                });
            }
            CompletableFuture<Void> bannerFuture = null;
            if (banner != null) {
                bannerFuture = banner.asByteArray(server.getApi()).thenAccept(bytes -> {
                    String base64Banner = "data:image/" + banner.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
                    body.put("banner", base64Banner);
                });
            }
            CompletableFuture<Void> future;
            List<CompletableFuture<Void>> futureList = new ArrayList<>();
            if (iconFuture != null) {
                futureList.add(iconFuture);
            }
            if (splashFuture != null) {
                futureList.add(splashFuture);
            }
            if (bannerFuture != null) {
                futureList.add(bannerFuture);
            }
            future = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()]));
            tasks.add(future.thenCompose(aVoid -> new RestRequest<Void>(server.getApi(), RestMethod.PATCH, RestEndpoint.SERVER).setUrlParameters(server.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> null)));
        } else {
            tasks.add(new RestRequest<Void>(server.getApi(), RestMethod.PATCH, RestEndpoint.SERVER).setUrlParameters(server.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> null));
        }
    }
    CompletableFuture<?>[] tasksArray = tasks.toArray(new CompletableFuture<?>[tasks.size()]);
    return CompletableFuture.allOf(tasksArray);
}
Also used : ServerChannel(org.javacord.api.entity.channel.ServerChannel) URL(java.net.URL) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RestMethod(org.javacord.core.util.rest.RestMethod) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FileContainer(org.javacord.core.util.FileContainer) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DiscordEntity(org.javacord.api.entity.DiscordEntity) Region(org.javacord.api.entity.Region) Locale(java.util.Locale) Map(java.util.Map) Icon(org.javacord.api.entity.Icon) RestRequest(org.javacord.core.util.rest.RestRequest) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) DefaultMessageNotificationLevel(org.javacord.api.entity.server.DefaultMessageNotificationLevel) BufferedImage(java.awt.image.BufferedImage) Collection(java.util.Collection) DiscordApiImpl(org.javacord.core.DiscordApiImpl) File(java.io.File) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) ExplicitContentFilterLevel(org.javacord.api.entity.server.ExplicitContentFilterLevel) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Base64(java.util.Base64) List(java.util.List) User(org.javacord.api.entity.user.User) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Role(org.javacord.api.entity.permission.Role) VerificationLevel(org.javacord.api.entity.server.VerificationLevel) Server(org.javacord.api.entity.server.Server) ServerUpdaterDelegate(org.javacord.api.entity.server.internal.ServerUpdaterDelegate) InputStream(java.io.InputStream) User(org.javacord.api.entity.user.User) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayList(java.util.ArrayList) Role(org.javacord.api.entity.permission.Role) CompletableFuture(java.util.concurrent.CompletableFuture) RestRequest(org.javacord.core.util.rest.RestRequest) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) HashSet(java.util.HashSet)

Example 4 with DiscordApiImpl

use of org.javacord.core.DiscordApiImpl in project Javacord by BtoBastian.

the class MessageContextMenuUpdaterDelegateImpl method updateForServer.

@Override
public CompletableFuture<MessageContextMenu> updateForServer(Server server) {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    prepareBody(body);
    return new RestRequest<MessageContextMenu>(server.getApi(), RestMethod.PATCH, RestEndpoint.SERVER_APPLICATION_COMMANDS).setUrlParameters(String.valueOf(server.getApi().getClientId()), server.getIdAsString(), String.valueOf(commandId)).setBody(body).execute(result -> new MessageContextMenuImpl((DiscordApiImpl) server.getApi(), result.getJsonBody()));
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DiscordApiImpl(org.javacord.core.DiscordApiImpl) MessageContextMenu(org.javacord.api.interaction.MessageContextMenu)

Example 5 with DiscordApiImpl

use of org.javacord.core.DiscordApiImpl in project Javacord by BtoBastian.

the class SlashCommandUpdaterDelegateImpl method updateForServer.

@Override
public CompletableFuture<SlashCommand> updateForServer(Server server) {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    prepareBody(body);
    return new RestRequest<SlashCommand>(server.getApi(), RestMethod.PATCH, RestEndpoint.SERVER_APPLICATION_COMMANDS).setUrlParameters(String.valueOf(server.getApi().getClientId()), server.getIdAsString(), String.valueOf(commandId)).setBody(body).execute(result -> new SlashCommandImpl((DiscordApiImpl) server.getApi(), result.getJsonBody()));
}
Also used : SlashCommand(org.javacord.api.interaction.SlashCommand) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DiscordApiImpl(org.javacord.core.DiscordApiImpl)

Aggregations

DiscordApiImpl (org.javacord.core.DiscordApiImpl)13 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)10 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 ArrayList (java.util.ArrayList)4 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)3 BufferedImage (java.awt.image.BufferedImage)3 File (java.io.File)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 List (java.util.List)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 Icon (org.javacord.api.entity.Icon)3 FileContainer (org.javacord.core.util.FileContainer)3 RestEndpoint (org.javacord.core.util.rest.RestEndpoint)3 RestMethod (org.javacord.core.util.rest.RestMethod)3 RestRequest (org.javacord.core.util.rest.RestRequest)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Arrays (java.util.Arrays)2