Search in sources :

Example 1 with AccountTypeException

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

the class DLUser method getOAuth2Application.

/**
 * Gets the OAuth2 application of the logged in user, if {@link User#isBot()}
 * returns true
 *
 * @return A Future that completes with a new {@link OAuth2Application} if
 *         successful.
 * @throws AccountTypeException
 *             Thrown if the account the client is logged in as is a user
 *             account.
 */
public CompletableFuture<OAuth2Application> getOAuth2Application() {
    if (!isBot()) {
        throw new AccountTypeException("Cannot fetch the OAuth2Application details of a User Account.");
    }
    CompletableFuture<OAuth2Application> future = new CompletableFuture<>();
    CompletableFuture<OAuthApplicationJSON> cf = getLoader().rest.request(Methods.GET, Endpoints.currentOAuthApplication, new RESTOptions(), OAuthApplicationJSON.class);
    cf.thenAcceptAsync(appData -> {
        IUser owner = EntityRegistry.addUser(appData.owner);
        future.complete(new OAuth2Application(appData, owner));
    });
    cf.exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });
    return future;
}
Also used : OAuthApplicationJSON(io.discloader.discloader.network.json.OAuthApplicationJSON) CompletableFuture(java.util.concurrent.CompletableFuture) RESTOptions(io.discloader.discloader.network.rest.RESTOptions) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) IUser(io.discloader.discloader.entity.user.IUser)

Example 2 with AccountTypeException

use of io.discloader.discloader.common.exceptions.AccountTypeException 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)

Example 3 with AccountTypeException

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

the class DiscLoader method syncGuilds.

/**
 * Syncs guilds to client if the logged in user is not a bot
 *
 * @param guilds
 *            the guilds to sync
 * @throws GuildSyncException
 * @throws AccountTypeException
 */
public void syncGuilds(IGuild... guilds) throws GuildSyncException, AccountTypeException {
    if (user.isBot())
        throw new AccountTypeException("Only user accounts are allowed to sync guilds");
    String[] ids = new String[guilds.length];
    for (int i = 0; i < guilds.length; i++) {
        if (isGuildSyncing(guilds[i]))
            throw new GuildSyncException("Cannot syncing a guild that is currently syncing");
        ids[i] = Long.toUnsignedString(guilds[i].getID());
    }
    Packet packet = new Packet(12, ids);
    socket.send(packet, true);
}
Also used : Packet(io.discloader.discloader.entity.sendable.Packet) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) GuildSyncException(io.discloader.discloader.common.exceptions.GuildSyncException)

Example 4 with AccountTypeException

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

the class DiscLoader method syncGuilds.

/**
 * Syncs guilds to client if the logged in user is not a bot
 *
 * @param guildIDs
 *            the ids of the guilds to sync
 * @throws AccountTypeException
 * @throws GuildSyncException
 */
public void syncGuilds(long... guildIDs) throws AccountTypeException, GuildSyncException {
    if (user.isBot())
        throw new AccountTypeException("Only user accounts are allowed to sync guilds");
    String[] ids = new String[guildIDs.length];
    for (int i = 0; i < guildIDs.length; i++) {
        ids[i] = Long.toUnsignedString(guildIDs[i], 10);
    }
    Packet packet = new Packet(12, ids);
    socket.send(packet, true);
}
Also used : Packet(io.discloader.discloader.entity.sendable.Packet) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException)

Example 5 with AccountTypeException

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

the class DiscLoader method syncGuilds.

/**
 * Syncs guilds to client if the logged in user is not a bot
 *
 * @param guildIDs
 *            the ids of the guilds to sync
 * @throws AccountTypeException
 * @throws GuildSyncException
 */
public void syncGuilds(String... guildIDs) throws AccountTypeException, GuildSyncException {
    if (user.isBot())
        throw new AccountTypeException("Only user accounts are allowed to sync guilds");
    for (String id : guildIDs) {
        if (isGuildSyncing(id))
            throw new GuildSyncException("Cannot syncing a guild that is currently syncing");
    }
    Packet packet = new Packet(12, guildIDs);
    socket.send(packet, true);
}
Also used : Packet(io.discloader.discloader.entity.sendable.Packet) AccountTypeException(io.discloader.discloader.common.exceptions.AccountTypeException) GuildSyncException(io.discloader.discloader.common.exceptions.GuildSyncException)

Aggregations

AccountTypeException (io.discloader.discloader.common.exceptions.AccountTypeException)5 Packet (io.discloader.discloader.entity.sendable.Packet)3 GuildSyncException (io.discloader.discloader.common.exceptions.GuildSyncException)2 HttpResponse (com.mashape.unirest.http.HttpResponse)1 Callback (com.mashape.unirest.http.async.Callback)1 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)1 BaseRequest (com.mashape.unirest.request.BaseRequest)1 HttpRequest (com.mashape.unirest.request.HttpRequest)1 DiscLoader (io.discloader.discloader.common.DiscLoader)1 RawEvent (io.discloader.discloader.common.event.RawEvent)1 DiscordException (io.discloader.discloader.common.exceptions.DiscordException)1 PermissionsException (io.discloader.discloader.common.exceptions.PermissionsException)1 UnauthorizedException (io.discloader.discloader.common.exceptions.UnauthorizedException)1 IUser (io.discloader.discloader.entity.user.IUser)1 ExceptionJSON (io.discloader.discloader.network.json.ExceptionJSON)1 OAuthApplicationJSON (io.discloader.discloader.network.json.OAuthApplicationJSON)1 RESTOptions (io.discloader.discloader.network.rest.RESTOptions)1 DLUtil.gson (io.discloader.discloader.util.DLUtil.gson)1 DateFormat (java.text.DateFormat)1 ParseException (java.text.ParseException)1