Search in sources :

Example 1 with HttpResponse

use of com.mashape.unirest.http.HttpResponse in project Javacord by BtoBastian.

the class ImplDiscordAPI method updateProfile.

@Override
public Future<Void> updateProfile(final String newUsername, String newEmail, final String newPassword, final BufferedImage newAvatar) {
    logger.debug("Trying to update profile (username: {}, email: {}, password: {}, change avatar: {}", newUsername, email, newPassword == null ? "null" : newPassword.replaceAll(".", "*"), newAvatar != null);
    String avatarString = getYourself().getAvatarId();
    if (newAvatar != null) {
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(newAvatar, "jpg", os);
            avatarString = "data:image/jpg;base64," + BaseEncoding.base64().encode(os.toByteArray());
        } catch (IOException ignored) {
        }
    }
    final JSONObject params = new JSONObject().put("username", newUsername == null ? getYourself().getName() : newUsername).put("avatar", avatarString == null ? JSONObject.NULL : avatarString);
    if (email != null && password != null) {
        // do not exist in bot accounts
        params.put("email", newEmail == null ? email : newEmail).put("password", password);
    }
    if (newPassword != null) {
        params.put("new_password", newPassword);
    }
    return getThreadPool().getExecutorService().submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            HttpResponse<JsonNode> response = Unirest.patch("https://discordapp.com/api/v6/users/@me").header("authorization", token).header("Content-Type", "application/json").body(params.toString()).asJson();
            checkResponse(response);
            logger.info("Updated profile (username: {}, email: {}, password: {}, change avatar: {}", newUsername, email, newPassword == null ? "null" : newPassword.replaceAll(".", "*"), newAvatar != null);
            ((ImplUser) getYourself()).setAvatarId(response.getBody().getObject().getString("avatar"));
            if (response.getBody().getObject().has("email") && !response.getBody().getObject().isNull("email")) {
                setEmail(response.getBody().getObject().getString("email"));
            }
            setToken(response.getBody().getObject().getString("token"), token.startsWith("Bot "));
            final String oldName = getYourself().getName();
            ((ImplUser) getYourself()).setName(response.getBody().getObject().getString("username"));
            if (newPassword != null) {
                password = newPassword;
            }
            if (!getYourself().getName().equals(oldName)) {
                getThreadPool().getSingleThreadExecutorService("listeners").submit(new Runnable() {

                    @Override
                    public void run() {
                        List<UserChangeNameListener> listeners = getListeners(UserChangeNameListener.class);
                        synchronized (listeners) {
                            for (UserChangeNameListener listener : listeners) {
                                listener.onUserChangeName(ImplDiscordAPI.this, getYourself(), oldName);
                            }
                        }
                    }
                });
            }
            return null;
        }
    });
}
Also used : JSONObject(org.json.JSONObject) HttpResponse(com.mashape.unirest.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) RateLimitedException(de.btobastian.javacord.exceptions.RateLimitedException) BadResponseException(de.btobastian.javacord.exceptions.BadResponseException) IOException(java.io.IOException) NotSupportedForBotsException(de.btobastian.javacord.exceptions.NotSupportedForBotsException) ExecutionException(java.util.concurrent.ExecutionException) PermissionsException(de.btobastian.javacord.exceptions.PermissionsException) UserChangeNameListener(de.btobastian.javacord.listener.user.UserChangeNameListener)

Example 2 with HttpResponse

use of com.mashape.unirest.http.HttpResponse in project Javacord by BtoBastian.

the class ImplDiscordAPI method parseInvite.

@Override
public Future<Invite> parseInvite(final String invite, FutureCallback<Invite> callback) {
    final String inviteCode = invite.replace("https://discord.gg/", "").replace("http://discord.gg/", "");
    ListenableFuture<Invite> future = getThreadPool().getListeningExecutorService().submit(new Callable<Invite>() {

        @Override
        public Invite call() throws Exception {
            logger.debug("Trying to parse invite {} (parsed code: {})", invite, inviteCode);
            HttpResponse<JsonNode> response = Unirest.get("https://discordapp.com/api/v6/invite/" + inviteCode).header("authorization", token).asJson();
            checkResponse(response);
            logger.debug("Parsed invite {} (parsed code: {})", invite, inviteCode);
            return new ImplInvite(ImplDiscordAPI.this, response.getBody().getObject());
        }
    });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}
Also used : HttpResponse(com.mashape.unirest.http.HttpResponse) ImplInvite(de.btobastian.javacord.entities.impl.ImplInvite) ImplInvite(de.btobastian.javacord.entities.impl.ImplInvite) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) RateLimitedException(de.btobastian.javacord.exceptions.RateLimitedException) BadResponseException(de.btobastian.javacord.exceptions.BadResponseException) IOException(java.io.IOException) NotSupportedForBotsException(de.btobastian.javacord.exceptions.NotSupportedForBotsException) ExecutionException(java.util.concurrent.ExecutionException) PermissionsException(de.btobastian.javacord.exceptions.PermissionsException)

Example 3 with HttpResponse

use of com.mashape.unirest.http.HttpResponse in project Javacord by BtoBastian.

the class ImplChannel method sendFile.

@Override
public Future<Message> sendFile(final File file, final String comment, FutureCallback<Message> callback) {
    final MessageReceiver receiver = this;
    ListenableFuture<Message> future = api.getThreadPool().getListeningExecutorService().submit(new Callable<Message>() {

        @Override
        public Message call() throws Exception {
            logger.debug("Trying to send a file in channel {} (name: {}, comment: {})", ImplChannel.this, file.getName(), comment);
            api.checkRateLimit(null, RateLimitType.SERVER_MESSAGE, null, ImplChannel.this);
            MultipartBody body = Unirest.post("https://discordapp.com/api/v6/channels/" + id + "/messages").header("authorization", api.getToken()).field("file", file);
            if (comment != null) {
                body.field("content", comment);
            }
            HttpResponse<JsonNode> response = body.asJson();
            api.checkResponse(response);
            api.checkRateLimit(response, RateLimitType.SERVER_MESSAGE, null, ImplChannel.this);
            logger.debug("Sent a file in channel {} (name: {}, comment: {})", ImplChannel.this, file.getName(), comment);
            return new ImplMessage(response.getBody().getObject(), api, receiver);
        }
    });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}
Also used : ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) Message(de.btobastian.javacord.entities.message.Message) MessageReceiver(de.btobastian.javacord.entities.message.MessageReceiver) MultipartBody(com.mashape.unirest.request.body.MultipartBody) ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) HttpResponse(com.mashape.unirest.http.HttpResponse) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) JSONException(org.json.JSONException)

Example 4 with HttpResponse

use of com.mashape.unirest.http.HttpResponse in project Javacord by BtoBastian.

the class ImplChannel method sendFile.

@Override
public Future<Message> sendFile(final InputStream inputStream, final String filename, final String comment, FutureCallback<Message> callback) {
    final MessageReceiver receiver = this;
    ListenableFuture<Message> future = api.getThreadPool().getListeningExecutorService().submit(new Callable<Message>() {

        @Override
        public Message call() throws Exception {
            logger.debug("Trying to send an input stream in channel {} (comment: {})", ImplChannel.this, comment);
            api.checkRateLimit(null, RateLimitType.SERVER_MESSAGE, null, ImplChannel.this);
            MultipartBody body = Unirest.post("https://discordapp.com/api/v6/channels/" + id + "/messages").header("authorization", api.getToken()).field("file", inputStream, filename);
            if (comment != null) {
                body.field("content", comment);
            }
            HttpResponse<JsonNode> response = body.asJson();
            api.checkResponse(response);
            api.checkRateLimit(response, RateLimitType.SERVER_MESSAGE, null, ImplChannel.this);
            logger.debug("Sent an input stream in channel {} (comment: {})", ImplChannel.this, comment);
            return new ImplMessage(response.getBody().getObject(), api, receiver);
        }
    });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}
Also used : ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) Message(de.btobastian.javacord.entities.message.Message) MessageReceiver(de.btobastian.javacord.entities.message.MessageReceiver) MultipartBody(com.mashape.unirest.request.body.MultipartBody) ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) HttpResponse(com.mashape.unirest.http.HttpResponse) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) JSONException(org.json.JSONException)

Example 5 with HttpResponse

use of com.mashape.unirest.http.HttpResponse in project Javacord by BtoBastian.

the class ImplUser method sendFile.

@Override
public Future<Message> sendFile(final File file, final String comment, FutureCallback<Message> callback) {
    final MessageReceiver receiver = this;
    ListenableFuture<Message> future = api.getThreadPool().getListeningExecutorService().submit(new Callable<Message>() {

        @Override
        public Message call() throws Exception {
            logger.debug("Trying to send a file to user {} (name: {}, comment: {})", ImplUser.this, file.getName(), comment);
            api.checkRateLimit(null, RateLimitType.PRIVATE_MESSAGE, null, null);
            MultipartBody body = Unirest.post("https://discordapp.com/api/v6/channels/" + getUserChannelIdBlocking() + "/messages").header("authorization", api.getToken()).field("file", file);
            if (comment != null) {
                body.field("content", comment);
            }
            HttpResponse<JsonNode> response = body.asJson();
            api.checkResponse(response);
            api.checkRateLimit(response, RateLimitType.PRIVATE_MESSAGE, null, null);
            logger.debug("Sent a file to user {} (name: {}, comment: {})", ImplUser.this, file.getName(), comment);
            return new ImplMessage(response.getBody().getObject(), api, receiver);
        }
    });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}
Also used : ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) Message(de.btobastian.javacord.entities.message.Message) MessageReceiver(de.btobastian.javacord.entities.message.MessageReceiver) MultipartBody(com.mashape.unirest.request.body.MultipartBody) ImplMessage(de.btobastian.javacord.entities.message.impl.ImplMessage) HttpResponse(com.mashape.unirest.http.HttpResponse) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException)

Aggregations

HttpResponse (com.mashape.unirest.http.HttpResponse)16 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)6 Message (de.btobastian.javacord.entities.message.Message)6 MessageReceiver (de.btobastian.javacord.entities.message.MessageReceiver)6 ImplMessage (de.btobastian.javacord.entities.message.impl.ImplMessage)6 JSONException (org.json.JSONException)6 Test (org.junit.Test)6 MultipartBody (com.mashape.unirest.request.body.MultipartBody)4 MalformedURLException (java.net.MalformedURLException)3 HttpResponseFactory (org.apache.http.HttpResponseFactory)3 StringEntity (org.apache.http.entity.StringEntity)3 DefaultHttpResponseFactory (org.apache.http.impl.DefaultHttpResponseFactory)3 BasicStatusLine (org.apache.http.message.BasicStatusLine)3 JSONObject (org.json.JSONObject)3 JsonNode (com.mashape.unirest.http.JsonNode)2 BadResponseException (de.btobastian.javacord.exceptions.BadResponseException)2 NotSupportedForBotsException (de.btobastian.javacord.exceptions.NotSupportedForBotsException)2 PermissionsException (de.btobastian.javacord.exceptions.PermissionsException)2 RateLimitedException (de.btobastian.javacord.exceptions.RateLimitedException)2 TypedException (io.javalin.util.TypedException)2