Search in sources :

Example 6 with PermissionsException

use of io.discloader.discloader.common.exceptions.PermissionsException in project DiscLoader by R3alCl0ud.

the class Guild method createTextChannel.

@Override
public CompletableFuture<IGuildTextChannel> createTextChannel(String name, IChannelCategory category, IOverwrite... overwrites) {
    CompletableFuture<IGuildTextChannel> future = new CompletableFuture<>();
    if (!hasPermission(Permissions.MANAGE_CHANNELS)) {
        PermissionsException ex = new PermissionsException("Insufficient Permissions");
        future.completeExceptionally(ex);
        // return early
        return future;
    }
    ChannelPayload data = new ChannelPayload(name, ChannelTypes.TEXT, overwrites);
    data.setParent(category);
    CompletableFuture<ChannelJSON> cf = getLoader().rest.request(Methods.POST, Endpoints.guildChannels(getID()), new RESTOptions(data), ChannelJSON.class);
    cf.thenAcceptAsync(channelJSON -> {
        IGuildTextChannel channel = (IGuildTextChannel) EntityBuilder.getChannelFactory().buildChannel(channelJSON, getLoader(), this, false);
        future.complete(channel);
    });
    cf.exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });
    return future;
}
Also used : ChannelJSON(io.discloader.discloader.network.json.ChannelJSON) CompletableFuture(java.util.concurrent.CompletableFuture) RESTOptions(io.discloader.discloader.network.rest.RESTOptions) ChannelPayload(io.discloader.discloader.network.rest.payloads.ChannelPayload) IGuildTextChannel(io.discloader.discloader.entity.channel.IGuildTextChannel) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException)

Example 7 with PermissionsException

use of io.discloader.discloader.common.exceptions.PermissionsException in project DiscLoader by R3alCl0ud.

the class GuildEmoji method setName.

@Override
public CompletableFuture<IGuildEmoji> setName(String name) {
    if (!guild.hasPermission(Permissions.MANAGE_EMOJIS)) {
        throw new PermissionsException("Insufficient Permissions: \"MANAGE_EMOJIS\" is required to use this endpoint");
    }
    CompletableFuture<IGuildEmoji> future = new CompletableFuture<>();
    JSONObject payload = new JSONObject().put("name", name);
    IEventListener el = new EventListenerAdapter() {

        @Override
        public void GuildEmojiUpdate(GuildEmojiUpdateEvent event) {
            if (getID() == event.getEmoji().getID()) {
                future.complete(event.getEmoji());
                getLoader().removeEventListener(this);
            }
        }
    };
    getLoader().addEventListener(el).rest.request(Methods.PATCH, Endpoints.guildEmoji(getGuild().getID(), getID()), new RESTOptions(payload), EmojiJSON.class).exceptionally(ex -> {
        future.completeExceptionally(ex);
        getLoader().removeEventListener(el);
        return null;
    });
    return future;
}
Also used : IGuildEmoji(io.discloader.discloader.entity.guild.IGuildEmoji) GuildEmojiUpdateEvent(io.discloader.discloader.common.event.guild.emoji.GuildEmojiUpdateEvent) IEventListener(io.discloader.discloader.common.event.IEventListener) CompletableFuture(java.util.concurrent.CompletableFuture) JSONObject(org.json.JSONObject) RESTOptions(io.discloader.discloader.network.rest.RESTOptions) EventListenerAdapter(io.discloader.discloader.common.event.EventListenerAdapter) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException) EmojiJSON(io.discloader.discloader.network.json.EmojiJSON)

Example 8 with PermissionsException

use of io.discloader.discloader.common.exceptions.PermissionsException in project DiscLoader by R3alCl0ud.

the class Message method edit.

/**
 * Edit's the messages content. Only possible if the {@link DiscLoader loader}
 * is the message's {@link #author}
 *
 * @param content
 *            The new content of the message
 * @param embed
 *            The new embed for the message
 * @return A Future that completes with {@literal this} when sucessfull
 */
@Override
public CompletableFuture<IMessage> edit(String content, RichEmbed embed) {
    CompletableFuture<IMessage> future = new CompletableFuture<>();
    if (!canEdit()) {
        future.completeExceptionally(new PermissionsException("Only messages author by you can be editted"));
        return future;
    }
    SendableMessage sendable = null;
    Attachment attachment = null;
    File file = null;
    if (embed != null) {
        if ((embed.getThumbnail() != null && embed.getThumbnail().resource != null)) {
            attachment = new Attachment(embed.getThumbnail().resource.getName());
        }
        if (embed.getThumbnail() != null && embed.getThumbnail().file != null) {
            attachment = new Attachment(embed.getThumbnail().file.getName());
        }
        if ((embed.getImage() != null && embed.getImage().resource != null)) {
            attachment = new Attachment(embed.getImage().resource.getName());
        }
        if (embed.getImage() != null && embed.getImage().file != null) {
            attachment = new Attachment(embed.getImage().file.getName());
        }
    }
    sendable = new SendableMessage(content, false, embed, attachment, file);
    CompletableFuture<MessageJSON> cf = loader.rest.request(Methods.PATCH, Endpoints.message(getChannel().getID(), getID()), new RESTOptions(sendable), MessageJSON.class);
    cf.thenAcceptAsync(messageJSON -> {
        future.complete(EntityBuilder.getChannelFactory().buildMessage(channel, messageJSON));
    });
    cf.exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) RESTOptions(io.discloader.discloader.network.rest.RESTOptions) MessageJSON(io.discloader.discloader.network.json.MessageJSON) SendableMessage(io.discloader.discloader.entity.sendable.SendableMessage) IMessage(io.discloader.discloader.entity.message.IMessage) Attachment(io.discloader.discloader.entity.sendable.Attachment) IMessageAttachment(io.discloader.discloader.entity.message.IMessageAttachment) File(java.io.File) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException)

Example 9 with PermissionsException

use of io.discloader.discloader.common.exceptions.PermissionsException in project DiscLoader by R3alCl0ud.

the class Message method deleteAllReactions.

@Override
public CompletableFuture<IMessage> deleteAllReactions() {
    CompletableFuture<IMessage> future = new CompletableFuture<>();
    if (channel instanceof IGuildChannel) {
        if (!((IGuildChannel) channel).permissionsOf(guild.getCurrentMember()).hasPermission(Permissions.MANAGE_MESSAGES)) {
            future.completeExceptionally(new PermissionsException());
            return future;
        }
    }
    CompletableFuture<Void> cf = loader.rest.request(Methods.DELETE, Endpoints.messageReactions(getChannel().getID(), getID()), new RESTOptions(), Void.class);
    cf.thenAcceptAsync(Null -> {
        future.complete(this);
    });
    cf.exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) RESTOptions(io.discloader.discloader.network.rest.RESTOptions) IGuildChannel(io.discloader.discloader.entity.channel.IGuildChannel) IMessage(io.discloader.discloader.entity.message.IMessage) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException)

Example 10 with PermissionsException

use of io.discloader.discloader.common.exceptions.PermissionsException in project DiscLoader by R3alCl0ud.

the class RESTQueue method handle.

public void handle() {
    try {
        if (waiting || queue.size() == 0 || globalLimit) {
            return;
        }
        waiting = true;
        final APIRequest apiRequest = queue.get(0);
        BaseRequest request = apiRequest.createRequest();
        request = addHeaders(request, apiRequest.auth, apiRequest.multi);
        request.asStringAsync(new Callback<String>() {

            @Override
            public void cancelled() {
                apiRequest.future.completeExceptionally(new Throwable());
            }

            @Override
            public void completed(HttpResponse<String> response) {
                Map<String, List<String>> headers = response.getHeaders();
                headers.forEach((name, value) -> {
                    switch(name) {
                        case "X-RateLimit-Limit":
                            rateLimit = Integer.parseInt(value.get(0), 10);
                            break;
                        case "X-RateLimit-Remaining":
                            remaining = Integer.parseInt(value.get(0), 10);
                            break;
                        case "x-ratelimit-reset":
                        case "X-RateLimit-Reset":
                            resetTime = (Long.parseLong(value.get(0), 10) * 1000L);
                            break;
                        case "X-RateLimit-Global":
                            globalLimit = Boolean.parseBoolean(value.get(0));
                            break;
                    }
                });
                RawEvent event = new RawEvent(loader, response);
                DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
                try {
                    timeDifference = Date.from(Instant.now()).getTime() - df.parse(headers.get("Date").get(0)).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int code = response.getStatus();
                if (code == 429) {
                    Thread wait = new Thread("Ratelimit resetting - " + apiRequest.url) {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(Integer.parseInt(headers.get("Retry-After").get(0), 10) + 500);
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            waiting = false;
                            globalLimit = false;
                            handle();
                        }
                    };
                    wait.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
                    wait.setDaemon(true);
                    wait.start();
                    return;
                } else if (code != 200 && code != 201 && code != 204 && code != 304) {
                    queue.remove(apiRequest);
                    loader.emit(event);
                    loader.emit("RawPacket", event);
                    ExceptionJSON data = gson.fromJson(response.getBody(), ExceptionJSON.class);
                    switch(code) {
                        case 401:
                            apiRequest.future.completeExceptionally(new UnauthorizedException(response.getBody()));
                            break;
                        case 403:
                            switch(data.code) {
                                case 20002:
                                    apiRequest.future.completeExceptionally(new AccountTypeException(data));
                                    break;
                                case 50013:
                                    apiRequest.future.completeExceptionally(new PermissionsException(data));
                                    break;
                                default:
                                    apiRequest.future.completeExceptionally(new UnauthorizedException(response.getBody()));
                                    break;
                            }
                            break;
                        default:
                            apiRequest.future.completeExceptionally(new DiscordException(data));
                            break;
                    }
                } else {
                    queue.remove(apiRequest);
                    loader.emit(event);
                    loader.emit("RawPacket", event);
                    apiRequest.future.complete(response.getBody());
                }
                globalLimit = false;
                long waitTime = ((resetTime - System.currentTimeMillis()) + timeDifference + 500);
                if (remaining == 0 && waitTime > 0) {
                    Thread wait = new Thread("REST Waiting - " + apiRequest.url) {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(waitTime);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            waiting = false;
                            handle();
                        }
                    };
                    wait.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
                    wait.setDaemon(true);
                    wait.start();
                } else {
                    waiting = false;
                    handle();
                }
            }

            @Override
            public void failed(UnirestException e) {
                apiRequest.future.completeExceptionally(e);
                handle();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) HttpRequest(com.mashape.unirest.request.HttpRequest) Instant(java.time.Instant) ArrayList(java.util.ArrayList) List(java.util.List) Callback(com.mashape.unirest.http.async.Callback) RawEvent(io.discloader.discloader.common.event.RawEvent) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException) DLUtil.gson(io.discloader.discloader.util.DLUtil.gson) HttpResponse(com.mashape.unirest.http.HttpResponse) DiscordException(io.discloader.discloader.common.exceptions.DiscordException) Map(java.util.Map) DiscLoader(io.discloader.discloader.common.DiscLoader) UnauthorizedException(io.discloader.discloader.common.exceptions.UnauthorizedException) ExceptionJSON(io.discloader.discloader.network.json.ExceptionJSON) ParseException(java.text.ParseException) BaseRequest(com.mashape.unirest.request.BaseRequest) DateFormat(java.text.DateFormat) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) RawEvent(io.discloader.discloader.common.event.RawEvent) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) PermissionsException(io.discloader.discloader.common.exceptions.PermissionsException) DiscordException(io.discloader.discloader.common.exceptions.DiscordException) UnauthorizedException(io.discloader.discloader.common.exceptions.UnauthorizedException) ParseException(java.text.ParseException) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) ExceptionJSON(io.discloader.discloader.network.json.ExceptionJSON) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) BaseRequest(com.mashape.unirest.request.BaseRequest) UnauthorizedException(io.discloader.discloader.common.exceptions.UnauthorizedException) DiscordException(io.discloader.discloader.common.exceptions.DiscordException) ParseException(java.text.ParseException) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

PermissionsException (io.discloader.discloader.common.exceptions.PermissionsException)20 RESTOptions (io.discloader.discloader.network.rest.RESTOptions)19 CompletableFuture (java.util.concurrent.CompletableFuture)19 JSONObject (org.json.JSONObject)10 IGuildMember (io.discloader.discloader.entity.guild.IGuildMember)7 ChannelJSON (io.discloader.discloader.network.json.ChannelJSON)7 EventListenerAdapter (io.discloader.discloader.common.event.EventListenerAdapter)6 IGuildTextChannel (io.discloader.discloader.entity.channel.IGuildTextChannel)5 IEventListener (io.discloader.discloader.common.event.IEventListener)4 IRole (io.discloader.discloader.entity.guild.IRole)3 GuildEmojiUpdateEvent (io.discloader.discloader.common.event.guild.emoji.GuildEmojiUpdateEvent)2 GuildMemberUpdateEvent (io.discloader.discloader.common.event.guild.member.GuildMemberUpdateEvent)2 IGuildChannel (io.discloader.discloader.entity.channel.IGuildChannel)2 IGuild (io.discloader.discloader.entity.guild.IGuild)2 IGuildEmoji (io.discloader.discloader.entity.guild.IGuildEmoji)2 IMessage (io.discloader.discloader.entity.message.IMessage)2 EmojiJSON (io.discloader.discloader.network.json.EmojiJSON)2 ChannelPayload (io.discloader.discloader.network.rest.payloads.ChannelPayload)2 ArrayList (java.util.ArrayList)2 HttpResponse (com.mashape.unirest.http.HttpResponse)1