Search in sources :

Example 1 with UserChangeNameListener

use of de.btobastian.javacord.listener.user.UserChangeNameListener 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 UserChangeNameListener

use of de.btobastian.javacord.listener.user.UserChangeNameListener in project Javacord by BtoBastian.

the class PresenceUpdateHandler method handle.

@Override
public void handle(JSONObject packet) {
    final User user = api.getOrCreateUser(packet.getJSONObject("user"));
    if (user == null) {
        return;
    }
    Server server = null;
    if (packet.has("guild_id")) {
        server = api.getServerById(packet.getString("guild_id"));
    }
    if (server != null) {
        // add user to server
        ((ImplServer) server).addMember(user);
    }
    if (server != null && packet.has("roles")) {
        JSONArray roleIds = packet.getJSONArray("roles");
        for (int i = 0; i < roleIds.length(); i++) {
            // add user to the role
            ((ImplRole) server.getRoleById(roleIds.getString(i))).addUserNoUpdate(user);
        }
    }
    // check status
    if (packet.has("status")) {
        UserStatus status = UserStatus.fromString(packet.getString("status"));
        final UserStatus oldStatus = user.getStatus();
        ((ImplUser) user).setStatus(status);
        listenerExecutorService.submit(new Runnable() {

            @Override
            public void run() {
                List<UserChangeStatusListener> listeners = api.getListeners(UserChangeStatusListener.class);
                synchronized (listeners) {
                    for (UserChangeStatusListener listener : listeners) {
                        try {
                            listener.onUserChangeStatus(api, user, oldStatus);
                        } catch (Throwable t) {
                            logger.warn("Uncaught exception in UserChangeStatusListener!", t);
                        }
                    }
                }
            }
        });
    }
    // check username
    if (packet.getJSONObject("user").has("username")) {
        String name = packet.getJSONObject("user").getString("username");
        if (!user.getName().equals(name)) {
            final String oldName = user.getName();
            ((ImplUser) user).setName(name);
            listenerExecutorService.submit(new Runnable() {

                @Override
                public void run() {
                    List<UserChangeNameListener> listeners = api.getListeners(UserChangeNameListener.class);
                    synchronized (listeners) {
                        for (UserChangeNameListener listener : listeners) {
                            try {
                                listener.onUserChangeName(api, user, oldName);
                            } catch (Throwable t) {
                                logger.warn("Uncaught exception in UserChangeNameListener!", t);
                            }
                        }
                    }
                }
            });
        }
    }
    // check game
    if (packet.has("game")) {
        String game;
        if (!packet.isNull("game") && packet.getJSONObject("game").has("name") && !packet.getJSONObject("game").isNull("name")) {
            game = packet.getJSONObject("game").get("name").toString();
        } else {
            game = null;
        }
        String oldGame = user.getGame();
        if ((game == null && oldGame != null) || (game != null && oldGame == null) || (game != null && !game.equals(oldGame))) {
            ((ImplUser) user).setGame(game);
            List<UserChangeGameListener> listeners = api.getListeners(UserChangeGameListener.class);
            synchronized (listeners) {
                for (UserChangeGameListener listener : listeners) {
                    try {
                        listener.onUserChangeGame(api, user, oldGame);
                    } catch (Throwable t) {
                        logger.warn("Uncaught exception in UserChangeGameListener!", t);
                    }
                }
            }
        }
    }
}
Also used : ImplRole(de.btobastian.javacord.entities.permissions.impl.ImplRole) ImplUser(de.btobastian.javacord.entities.impl.ImplUser) User(de.btobastian.javacord.entities.User) ImplServer(de.btobastian.javacord.entities.impl.ImplServer) UserChangeStatusListener(de.btobastian.javacord.listener.user.UserChangeStatusListener) Server(de.btobastian.javacord.entities.Server) ImplServer(de.btobastian.javacord.entities.impl.ImplServer) JSONArray(org.json.JSONArray) UserChangeGameListener(de.btobastian.javacord.listener.user.UserChangeGameListener) UserStatus(de.btobastian.javacord.entities.UserStatus) List(java.util.List) ImplUser(de.btobastian.javacord.entities.impl.ImplUser) UserChangeNameListener(de.btobastian.javacord.listener.user.UserChangeNameListener)

Aggregations

UserChangeNameListener (de.btobastian.javacord.listener.user.UserChangeNameListener)2 HttpResponse (com.mashape.unirest.http.HttpResponse)1 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)1 Server (de.btobastian.javacord.entities.Server)1 User (de.btobastian.javacord.entities.User)1 UserStatus (de.btobastian.javacord.entities.UserStatus)1 ImplServer (de.btobastian.javacord.entities.impl.ImplServer)1 ImplUser (de.btobastian.javacord.entities.impl.ImplUser)1 ImplRole (de.btobastian.javacord.entities.permissions.impl.ImplRole)1 BadResponseException (de.btobastian.javacord.exceptions.BadResponseException)1 NotSupportedForBotsException (de.btobastian.javacord.exceptions.NotSupportedForBotsException)1 PermissionsException (de.btobastian.javacord.exceptions.PermissionsException)1 RateLimitedException (de.btobastian.javacord.exceptions.RateLimitedException)1 UserChangeGameListener (de.btobastian.javacord.listener.user.UserChangeGameListener)1 UserChangeStatusListener (de.btobastian.javacord.listener.user.UserChangeStatusListener)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 List (java.util.List)1 ExecutionException (java.util.concurrent.ExecutionException)1 JSONArray (org.json.JSONArray)1