Search in sources :

Example 11 with Message

use of org.javacord.api.entity.message.Message in project Javacord by BtoBastian.

the class MessageCacheImpl method clean.

/**
 * Cleans the cache.
 */
public void clean() {
    Instant minAge = Instant.now().minus(storageTimeInSeconds, ChronoUnit.SECONDS);
    api.getMessageCacheLock().lock();
    try {
        messages.removeIf(messageRef -> Optional.ofNullable(messageRef.get()).map(message -> !message.isCachedForever() && message.getCreationTimestamp().isBefore(minAge)).orElse(true));
        long foreverCachedAmount = messages.stream().map(Reference::get).filter(Objects::nonNull).filter(Message::isCachedForever).count();
        messages.removeAll(messages.stream().filter(messageRef -> Optional.ofNullable(messageRef.get()).map(message -> !message.isCachedForever()).orElse(true)).limit(Math.max(0, messages.size() - capacity - foreverCachedAmount)).collect(Collectors.toList()));
    } finally {
        api.getMessageCacheLock().unlock();
    }
}
Also used : Cleanupable(org.javacord.core.util.Cleanupable) DiscordApiImpl(org.javacord.core.DiscordApiImpl) Instant(java.time.Instant) Message(org.javacord.api.entity.message.Message) MessageCache(org.javacord.api.util.cache.MessageCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) ReferenceQueue(java.lang.ref.ReferenceQueue) ArrayList(java.util.ArrayList) Reference(java.lang.ref.Reference) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) List(java.util.List) Future(java.util.concurrent.Future) Logger(org.apache.logging.log4j.Logger) ChronoUnit(java.time.temporal.ChronoUnit) Optional(java.util.Optional) SoftReference(java.lang.ref.SoftReference) Comparator(java.util.Comparator) Collections(java.util.Collections) Instant(java.time.Instant) Objects(java.util.Objects)

Example 12 with Message

use of org.javacord.api.entity.message.Message in project Javacord by BtoBastian.

the class InteractionMessageBuilderDelegateImpl method checkForAttachmentsAndExecuteRequest.

private CompletableFuture<Message> checkForAttachmentsAndExecuteRequest(RestRequest<Message> request, ObjectNode body) {
    if (!attachments.isEmpty() || embeds.stream().anyMatch(EmbedBuilder::requiresAttachments)) {
        CompletableFuture<Message> future = new CompletableFuture<>();
        // We access files etc. so this should be async
        request.getApi().getThreadPool().getExecutorService().submit(() -> {
            try {
                List<FileContainer> tempAttachments = new ArrayList<>(attachments);
                // Add the attachments required for the embed
                for (EmbedBuilder embed : embeds) {
                    tempAttachments.addAll(((EmbedBuilderDelegateImpl) embed.getDelegate()).getRequiredAttachments());
                }
                addMultipartBodyToRequest(request, body, tempAttachments, request.getApi());
                request.execute(result -> request.getApi().getOrCreateMessage(request.getApi().getTextChannelById(result.getJsonBody().get("channel_id").asLong()).orElseThrow(() -> new NoSuchElementException("TextChannel is not cached")), result.getJsonBody())).whenComplete((message, throwable) -> {
                    if (throwable != null) {
                        future.completeExceptionally(throwable);
                    } else {
                        future.complete(message);
                    }
                });
            } catch (Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    } else {
        request.setBody(body);
        return request.execute(result -> request.getApi().getOrCreateMessage(request.getApi().getTextChannelById(result.getJsonBody().get("channel_id").asLong()).orElseThrow(() -> new NoSuchElementException("TextChannel is not cached")), result.getJsonBody()));
    }
}
Also used : InteractionCallbackDataFlag(org.javacord.api.interaction.callback.InteractionCallbackDataFlag) EmbedBuilder(org.javacord.api.entity.message.embed.EmbedBuilder) InteractionBase(org.javacord.api.interaction.InteractionBase) CompletableFuture(java.util.concurrent.CompletableFuture) RestMethod(org.javacord.core.util.rest.RestMethod) Message(org.javacord.api.entity.message.Message) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FileContainer(org.javacord.core.util.FileContainer) ArrayList(java.util.ArrayList) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) List(java.util.List) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) MessageComponentInteraction(org.javacord.api.interaction.MessageComponentInteraction) RestRequest(org.javacord.core.util.rest.RestRequest) EmbedBuilderDelegateImpl(org.javacord.core.entity.message.embed.EmbedBuilderDelegateImpl) InteractionImpl(org.javacord.core.interaction.InteractionImpl) NoSuchElementException(java.util.NoSuchElementException) EnumSet(java.util.EnumSet) InteractionMessageBuilderDelegate(org.javacord.api.entity.message.internal.InteractionMessageBuilderDelegate) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(org.javacord.api.entity.message.embed.EmbedBuilder) Message(org.javacord.api.entity.message.Message) ArrayList(java.util.ArrayList) FileContainer(org.javacord.core.util.FileContainer) NoSuchElementException(java.util.NoSuchElementException)

Example 13 with Message

use of org.javacord.api.entity.message.Message in project Javacord by BtoBastian.

the class MessageBuilderBaseDelegateImpl method edit.

@Override
public CompletableFuture<Message> edit(Message message, boolean updateAll) {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (updateAll || contentChanged) {
        body.put("content", strBuilder.toString());
    }
    prepareAllowedMentions(body);
    prepareEmbeds(body, updateAll || embedsChanged);
    prepareComponents(body, updateAll || componentsChanged);
    RestRequest<Message> request = new RestRequest<Message>(message.getApi(), RestMethod.PATCH, RestEndpoint.MESSAGE).setUrlParameters(Long.toUnsignedString(message.getChannel().getId()), Long.toUnsignedString(message.getId()));
    if (updateAll || attachmentsChanged) {
        return checkForAttachmentsAndExecuteRequest(message.getChannel(), body, request, true);
    } else {
        return executeRequestWithoutAttachments(message.getChannel(), body, request);
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Message(org.javacord.api.entity.message.Message)

Example 14 with Message

use of org.javacord.api.entity.message.Message in project Javacord by BtoBastian.

the class MessageBuilderBaseDelegateImpl method send.

@Override
public CompletableFuture<Message> send(TextChannel channel) {
    ObjectNode body = JsonNodeFactory.instance.objectNode().put("content", toString() == null ? "" : toString()).put("tts", tts);
    body.putArray("mentions");
    prepareAllowedMentions(body);
    prepareEmbeds(body, false);
    prepareComponents(body, false);
    if (nonce != null) {
        body.put("nonce", nonce);
    }
    if (!stickerIds.isEmpty()) {
        ArrayNode stickersNode = JsonNodeFactory.instance.objectNode().arrayNode();
        for (long stickerId : stickerIds) {
            stickersNode.add(stickerId);
        }
        body.set("sticker_ids", stickersNode);
    }
    if (replyingTo != null) {
        body.putObject("message_reference").put("message_id", replyingTo);
    }
    RestRequest<Message> request = new RestRequest<Message>(channel.getApi(), RestMethod.POST, RestEndpoint.MESSAGE).setUrlParameters(channel.getIdAsString());
    return checkForAttachmentsAndExecuteRequest(channel, body, request, false);
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Message(org.javacord.api.entity.message.Message) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Aggregations

Message (org.javacord.api.entity.message.Message)14 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 RestRequest (org.javacord.core.util.rest.RestRequest)6 Arrays (java.util.Arrays)5 Collections (java.util.Collections)5 TextChannel (org.javacord.api.entity.channel.TextChannel)5 EmbedBuilder (org.javacord.api.entity.message.embed.EmbedBuilder)5 DiscordApiImpl (org.javacord.core.DiscordApiImpl)5 RestEndpoint (org.javacord.core.util.rest.RestEndpoint)5 RestMethod (org.javacord.core.util.rest.RestMethod)5 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)4 Stream (java.util.stream.Stream)4 StreamSupport (java.util.stream.StreamSupport)4 DiscordApi (org.javacord.api.DiscordApi)4 Emoji (org.javacord.api.entity.emoji.Emoji)4