Search in sources :

Example 1 with RawEvent

use of io.discloader.discloader.common.event.RawEvent in project DiscLoader by R3alCl0ud.

the class GatewayListener method onFrame.

@Override
public void onFrame(WebSocket ws, WebSocketFrame frame) {
    RawEvent event = new RawEvent(loader, frame);
    loader.emit(event);
}
Also used : RawEvent(io.discloader.discloader.common.event.RawEvent)

Example 2 with RawEvent

use of io.discloader.discloader.common.event.RawEvent 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 RawEvent

use of io.discloader.discloader.common.event.RawEvent in project DiscLoader by R3alCl0ud.

the class Main method main.

public static void main(String... args) throws IOException {
    System.setProperty("http.agent", "DiscLoader");
    String content = "";
    if (new File("options.json").exists()) {
        Object[] lines = Files.readAllLines(Paths.get("./options.json")).toArray();
        for (Object line : lines) content += line;
        Options options = gson.fromJson(content, Options.class);
        token = options.auth.token;
    }
    boolean myBool = false;
    if (myBool && args.length > 1)
        System.out.println("hello");
    else
        System.out.println("fuck");
    DLOptions options = parseArgs(args);
    if (options.shards > 1) {
        ShardManager manager = new ShardManager(options);
        manager.addShardingListener(new ShardingListenerAdapter() {

            @Override
            public void onShardLaunched(ShardLaunchedEvent e) {
                LOGGER.info(String.format("Shard #%d: Launched", e.getShard().getShardID()));
                e.getShard().getLoader().addEventListener(new EventListenerAdapter() {

                    public void Ready(ReadyEvent e) {
                        for (Command command : CommandRegistry.commands.entries()) {
                            LOGGER.info(command.getUnlocalizedName());
                        }
                    }

                    @Override
                    public void RawPacket(RawEvent data) {
                        WebSocketFrame frame = data.getFrame();
                        if (data.isGateway() && frame.isTextFrame() && !frame.getPayloadText().contains("PRESENCE_UPDATE")) {
                        // LOGGER.fine(frame.getPayloadText());
                        } else if (data.isREST()) {
                            LOGGER.info(data.getHttpResponse().getBody());
                            LOGGER.info("" + data.getHttpResponse().getStatus());
                        }
                    }

                    @Override
                    public void GuildMessageCreate(GuildMessageCreateEvent e) {
                        if (e.getGuild().getID() != 282226852616077312l)
                            return;
                        if (e.getMessage().getContent().startsWith("logs")) {
                            String[] args = e.getMessage().getContent().split(" ");
                            if (args.length == 1) {
                            } else if (args.length == 2) {
                            }
                        }
                    }
                });
            }
        });
        manager.launchShards();
    } else {
        loader = new DiscLoader(options);
        loader.addEventListener(new EventListenerAdapter() {

            @Override
            public void MessageCreate(MessageCreateEvent e) {
                if (e.getMessage().getContent().equals("#$close")) {
                    e.getLoader().gateway.websocket.disconnect(1001);
                }
            }

            public void Ready(ReadyEvent e) {
                LOGGER.info(e.getLoader().user.getUsername());
                for (Command command : CommandRegistry.commands.entries()) {
                    LOGGER.info(command.getUnlocalizedName());
                }
                LOGGER.info(EntityRegistry.getGuildByID(282226852616077312l).getDefaultChannel().getName());
            // .sendMessage("testing 125");
            }

            @Override
            public void RawPacket(RawEvent data) {
                WebSocketFrame frame = data.getFrame();
                if (data.isGateway() && frame.isTextFrame() && !frame.getPayloadText().contains("PRESENCE_UPDATE")) {
                    LOGGER.info(frame.getPayloadText());
                } else if (data.isREST() && data.getHttpResponse() != null) {
                    LOGGER.info(data.getHttpResponse().getBody());
                }
            }
        });
        loader.login();
    }
}
Also used : DLOptions(io.discloader.discloader.common.DLOptions) RawEvent(io.discloader.discloader.common.event.RawEvent) ShardManager(io.discloader.discloader.common.ShardManager) ShardLaunchedEvent(io.discloader.discloader.common.event.sharding.ShardLaunchedEvent) ReadyEvent(io.discloader.discloader.common.event.ReadyEvent) MessageCreateEvent(io.discloader.discloader.common.event.message.MessageCreateEvent) GuildMessageCreateEvent(io.discloader.discloader.common.event.message.GuildMessageCreateEvent) DLOptions(io.discloader.discloader.common.DLOptions) Command(io.discloader.discloader.client.command.Command) DiscLoader(io.discloader.discloader.common.DiscLoader) EventListenerAdapter(io.discloader.discloader.common.event.EventListenerAdapter) WebSocketFrame(com.neovisionaries.ws.client.WebSocketFrame) GuildMessageCreateEvent(io.discloader.discloader.common.event.message.GuildMessageCreateEvent) File(java.io.File) ShardingListenerAdapter(io.discloader.discloader.common.event.sharding.ShardingListenerAdapter)

Example 4 with RawEvent

use of io.discloader.discloader.common.event.RawEvent in project DiscLoader by R3alCl0ud.

the class Route method handle.

public void handle() {
    if (waiting || rateLimiter.isLimited() || queue.isEmpty())
        return;
    waiting = true;
    Request<T> apiRequest = queue.remove(0);
    BaseRequest request = createRequest(apiRequest);
    request.asStringAsync(new Callback<String>() {

        @Override
        public void completed(HttpResponse<String> response) {
            try {
                rateLimiter.readHeaders(response.getHeaders());
                rest.loader.emit(new RawEvent(rest.loader, response));
                int code = response.getStatus();
                waiting = false;
                if (code == 429) {
                    queue.add(0, apiRequest);
                    rateLimiter.limitRoute(rest.isGlobally(), rateLimiter.retryIn());
                    // return early so handle() at the end of handle() doesn't get called
                    return;
                } else if (code >= 500 && code < 600) {
                    queue.add(0, apiRequest);
                } else if (code >= 400 && code < 500) {
                    apiRequest.getFuture().completeExceptionally(new DiscordException(gson.fromJson(response.getBody(), ExceptionJSON.class)));
                } else if (code == 204) {
                    apiRequest.getFuture().complete(null);
                } else {
                    T res = gson.fromJson(response.getBody(), cls);
                    apiRequest.getFuture().complete(res);
                }
                handle();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(UnirestException ex) {
            ex.printStackTrace();
            queue.add(0, apiRequest);
            handle();
        }

        @Override
        public void cancelled() {
            queue.add(0, apiRequest);
            handle();
        }
    });
}
Also used : RawEvent(io.discloader.discloader.common.event.RawEvent) ExceptionJSON(io.discloader.discloader.network.json.ExceptionJSON) BaseRequest(com.mashape.unirest.request.BaseRequest) DiscordException(io.discloader.discloader.common.exceptions.DiscordException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) DiscordException(io.discloader.discloader.common.exceptions.DiscordException)

Aggregations

RawEvent (io.discloader.discloader.common.event.RawEvent)4 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)2 BaseRequest (com.mashape.unirest.request.BaseRequest)2 DiscLoader (io.discloader.discloader.common.DiscLoader)2 DiscordException (io.discloader.discloader.common.exceptions.DiscordException)2 ExceptionJSON (io.discloader.discloader.network.json.ExceptionJSON)2 HttpResponse (com.mashape.unirest.http.HttpResponse)1 Callback (com.mashape.unirest.http.async.Callback)1 HttpRequest (com.mashape.unirest.request.HttpRequest)1 WebSocketFrame (com.neovisionaries.ws.client.WebSocketFrame)1 Command (io.discloader.discloader.client.command.Command)1 DLOptions (io.discloader.discloader.common.DLOptions)1 ShardManager (io.discloader.discloader.common.ShardManager)1 EventListenerAdapter (io.discloader.discloader.common.event.EventListenerAdapter)1 ReadyEvent (io.discloader.discloader.common.event.ReadyEvent)1 GuildMessageCreateEvent (io.discloader.discloader.common.event.message.GuildMessageCreateEvent)1 MessageCreateEvent (io.discloader.discloader.common.event.message.MessageCreateEvent)1 ShardLaunchedEvent (io.discloader.discloader.common.event.sharding.ShardLaunchedEvent)1 ShardingListenerAdapter (io.discloader.discloader.common.event.sharding.ShardingListenerAdapter)1 AccountTypeException (io.discloader.discloader.common.exceptions.AccountTypeException)1