Search in sources :

Example 11 with RestRequest

use of org.javacord.core.util.rest.RestRequest in project Javacord by BtoBastian.

the class WebhookBuilderDelegateImpl method create.

@Override
public CompletableFuture<IncomingWebhook> create() {
    if (name == null) {
        throw new IllegalStateException("Name is no optional parameter!");
    }
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    body.put("name", name);
    if (avatar != null) {
        return avatar.asByteArray(channel.getApi()).thenAccept(bytes -> {
            String base64Avatar = "data:image/" + avatar.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
            body.put("avatar", base64Avatar);
        }).thenCompose(aVoid -> new RestRequest<IncomingWebhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK).setUrlParameters(channel.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> new IncomingWebhookImpl(channel.getApi(), result.getJsonBody())));
    }
    return new RestRequest<IncomingWebhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK).setUrlParameters(channel.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> new IncomingWebhookImpl(channel.getApi(), result.getJsonBody()));
}
Also used : BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) CompletableFuture(java.util.concurrent.CompletableFuture) RestMethod(org.javacord.core.util.rest.RestMethod) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) IncomingWebhook(org.javacord.api.entity.webhook.IncomingWebhook) FileContainer(org.javacord.core.util.FileContainer) File(java.io.File) WebhookBuilderDelegate(org.javacord.api.entity.webhook.internal.WebhookBuilderDelegate) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Base64(java.util.Base64) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Icon(org.javacord.api.entity.Icon) RestRequest(org.javacord.core.util.rest.RestRequest) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) InputStream(java.io.InputStream) RestRequest(org.javacord.core.util.rest.RestRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) IncomingWebhook(org.javacord.api.entity.webhook.IncomingWebhook)

Example 12 with RestRequest

use of org.javacord.core.util.rest.RestRequest in project Javacord by BtoBastian.

the class WebhookUpdaterDelegateImpl method update.

@Override
public CompletableFuture<Webhook> update() {
    boolean patchWebhook = false;
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (name != null) {
        body.put("name", name);
        patchWebhook = true;
    }
    if (channel != null) {
        body.put("channel_id", channel.getIdAsString());
        patchWebhook = true;
    }
    if (updateAvatar) {
        if (avatar == null) {
            body.putNull("avatar");
        }
        patchWebhook = true;
    }
    if (patchWebhook) {
        if (avatar != null) {
            return avatar.asByteArray(webhook.getApi()).thenAccept(bytes -> {
                String base64Avatar = "data:image/" + avatar.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
                body.put("avatar", base64Avatar);
            }).thenCompose(aVoid -> setUrlParameters(new RestRequest<>(webhook.getApi(), RestMethod.PATCH, RestEndpoint.WEBHOOK)).setBody(body).setAuditLogReason(reason).execute(result -> WebhookImpl.createWebhook(webhook.getApi(), result.getJsonBody())));
        }
        return setUrlParameters(new RestRequest<>(webhook.getApi(), RestMethod.PATCH, RestEndpoint.WEBHOOK)).setBody(body).setAuditLogReason(reason).execute(result -> WebhookImpl.createWebhook(webhook.getApi(), result.getJsonBody()));
    } else {
        return CompletableFuture.completedFuture(webhook);
    }
}
Also used : Webhook(org.javacord.api.entity.webhook.Webhook) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) CompletableFuture(java.util.concurrent.CompletableFuture) RestMethod(org.javacord.core.util.rest.RestMethod) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) IncomingWebhook(org.javacord.api.entity.webhook.IncomingWebhook) FileContainer(org.javacord.core.util.FileContainer) File(java.io.File) WebhookUpdaterDelegate(org.javacord.api.entity.webhook.internal.WebhookUpdaterDelegate) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Base64(java.util.Base64) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Icon(org.javacord.api.entity.Icon) RestRequest(org.javacord.core.util.rest.RestRequest) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) Optional(java.util.Optional) InputStream(java.io.InputStream) RestRequest(org.javacord.core.util.rest.RestRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode)

Example 13 with RestRequest

use of org.javacord.core.util.rest.RestRequest in project Javacord by BtoBastian.

the class ChannelCategoryBuilderDelegateImpl method create.

@Override
public CompletableFuture<ChannelCategory> create() {
    ObjectNode body = JsonNodeFactory.instance.objectNode().put("type", 4);
    super.prepareBody(body);
    return new RestRequest<ChannelCategory>(server.getApi(), RestMethod.POST, RestEndpoint.SERVER_CHANNEL).setUrlParameters(server.getIdAsString()).setBody(body).setAuditLogReason(reason).execute(result -> server.getOrCreateChannelCategory(result.getJsonBody()));
}
Also used : RestRequest(org.javacord.core.util.rest.RestRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode)

Example 14 with RestRequest

use of org.javacord.core.util.rest.RestRequest in project Javacord by BtoBastian.

the class AccountUpdaterDelegateImpl method update.

@Override
public CompletableFuture<Void> update() {
    boolean patchAccount = false;
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (username != null) {
        body.put("username", username);
        patchAccount = true;
    }
    if (avatar != null) {
        patchAccount = true;
    }
    if (patchAccount) {
        if (avatar != null) {
            return avatar.asByteArray(api).thenAccept(bytes -> {
                String base64Avatar = "data:image/" + avatar.getFileType() + ";base64," + Base64.getEncoder().encodeToString(bytes);
                body.put("avatar", base64Avatar);
            }).thenCompose(aVoid -> new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.CURRENT_USER).setBody(body).execute(result -> null));
        }
        return new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.CURRENT_USER).setBody(body).execute(result -> null);
    } else {
        return CompletableFuture.completedFuture(null);
    }
}
Also used : BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) 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) File(java.io.File) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Base64(java.util.Base64) AccountUpdaterDelegate(org.javacord.api.internal.AccountUpdaterDelegate) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Icon(org.javacord.api.entity.Icon) RestRequest(org.javacord.core.util.rest.RestRequest) InputStream(java.io.InputStream) RestRequest(org.javacord.core.util.rest.RestRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode)

Example 15 with RestRequest

use of org.javacord.core.util.rest.RestRequest in project Javacord by BtoBastian.

the class RatelimitManager method queueRequest.

/**
 * Queues the given request.
 * This method is automatically called when using {@link RestRequest#execute(Function)}!
 *
 * @param request The request to queue.
 */
public void queueRequest(RestRequest<?> request) {
    final RatelimitBucket bucket;
    final boolean alreadyInQueue;
    synchronized (buckets) {
        // Search for a bucket that fits to this request
        bucket = buckets.stream().filter(b -> b.equals(request.getEndpoint(), request.getMajorUrlParameter().orElse(null))).findAny().orElseGet(() -> new RatelimitBucket(api, request.getEndpoint(), request.getMajorUrlParameter().orElse(null)));
        // Must be executed BEFORE adding the request to the queue
        alreadyInQueue = bucket.peekRequestFromQueue() != null;
        // Add the bucket to the set of buckets (does nothing if it's already in the set)
        buckets.add(bucket);
        // Add the request to the bucket's queue
        bucket.addRequestToQueue(request);
    }
    // If the bucket is already in the queue, there's nothing more to do
    if (alreadyInQueue) {
        return;
    }
    // Start working of the queue
    api.getThreadPool().getExecutorService().submit(() -> {
        RestRequest<?> currentRequest = bucket.peekRequestFromQueue();
        RestRequestResult result = null;
        long responseTimestamp = System.currentTimeMillis();
        while (currentRequest != null) {
            try {
                int sleepTime = bucket.getTimeTillSpaceGetsAvailable();
                if (sleepTime > 0) {
                    logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits", bucket, sleepTime);
                }
                // Sleep until space is available
                while (sleepTime > 0) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        logger.warn("We got interrupted while waiting for a rate limit!", e);
                    }
                    // Update in case something changed (e.g. because we hit a global ratelimit)
                    sleepTime = bucket.getTimeTillSpaceGetsAvailable();
                }
                // Execute the request
                result = currentRequest.executeBlocking();
                // Calculate the time offset, if it wasn't done before
                responseTimestamp = System.currentTimeMillis();
            } catch (Throwable t) {
                responseTimestamp = System.currentTimeMillis();
                if (currentRequest.getResult().isDone()) {
                    logger.warn("Received exception for a request that is already done. " + "This should not be able to happen!", t);
                }
                // Try to get the response from the exception if it exists
                if (t instanceof DiscordException) {
                    result = ((DiscordException) t).getResponse().map(RestRequestResponseInformationImpl.class::cast).map(RestRequestResponseInformationImpl::getRestRequestResult).orElse(null);
                }
                // Complete the request
                currentRequest.getResult().completeExceptionally(t);
            } finally {
                try {
                    // Calculate offset
                    calculateOffset(responseTimestamp, result);
                    // Handle the response
                    handleResponse(currentRequest, result, bucket, responseTimestamp);
                } catch (Throwable t) {
                    logger.warn("Encountered unexpected exception.", t);
                }
                // The request didn't finish, so let's try again
                if (!currentRequest.getResult().isDone()) {
                    continue;
                }
                // Poll a new quest
                synchronized (buckets) {
                    bucket.pollRequestFromQueue();
                    currentRequest = bucket.peekRequestFromQueue();
                    if (currentRequest == null) {
                        buckets.remove(bucket);
                    }
                }
            }
        }
    });
}
Also used : DiscordException(org.javacord.api.exception.DiscordException) Set(java.util.Set) CompletableFuture(java.util.concurrent.CompletableFuture) DiscordApiImpl(org.javacord.core.DiscordApiImpl) Function(java.util.function.Function) RestRequestResponseInformationImpl(org.javacord.core.util.rest.RestRequestResponseInformationImpl) HashSet(java.util.HashSet) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) Logger(org.apache.logging.log4j.Logger) OffsetDateTime(java.time.OffsetDateTime) RestRequestResult(org.javacord.core.util.rest.RestRequestResult) DateTimeFormatter(java.time.format.DateTimeFormatter) RestRequest(org.javacord.core.util.rest.RestRequest) Response(okhttp3.Response) RestRequestResponseInformationImpl(org.javacord.core.util.rest.RestRequestResponseInformationImpl) DiscordException(org.javacord.api.exception.DiscordException) RestRequestResult(org.javacord.core.util.rest.RestRequestResult)

Aggregations

RestRequest (org.javacord.core.util.rest.RestRequest)22 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)16 CompletableFuture (java.util.concurrent.CompletableFuture)13 RestEndpoint (org.javacord.core.util.rest.RestEndpoint)11 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)9 FileContainer (org.javacord.core.util.FileContainer)9 RestMethod (org.javacord.core.util.rest.RestMethod)9 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)7 ArrayList (java.util.ArrayList)7 DiscordApiImpl (org.javacord.core.DiscordApiImpl)7 BufferedImage (java.awt.image.BufferedImage)6 File (java.io.File)6 InputStream (java.io.InputStream)6 URL (java.net.URL)6 Icon (org.javacord.api.entity.Icon)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 Base64 (java.util.Base64)5 HashSet (java.util.HashSet)5 List (java.util.List)5 Message (org.javacord.api.entity.message.Message)5