Search in sources :

Example 1 with InvalidRequestException

use of net.robinfriedli.aiode.exceptions.InvalidRequestException in project aiode by robinfriedli.

the class PlaylistViewHandler method handle.

@Override
public void handle(HttpExchange exchange) throws IOException {
    Session session = null;
    try {
        String html = Files.readString(Path.of("html/playlist_view.html"));
        Map<String, String> parameterMap = ServerUtil.getParameters(exchange);
        String guildId = parameterMap.get("guildId");
        String name = parameterMap.get("name");
        boolean isPartitioned = Aiode.get().getGuildManager().getMode() == GuildManager.Mode.PARTITIONED;
        if (name != null && (guildId != null || !isPartitioned)) {
            session = sessionFactory.openSession();
            Playlist playlist = SearchEngine.searchLocalList(session, name, isPartitioned, guildId);
            if (playlist != null) {
                String createdUserId = playlist.getCreatedUserId();
                String createdUser;
                if (createdUserId.equals("system")) {
                    createdUser = playlist.getCreatedUser();
                } else {
                    User userById;
                    try {
                        userById = shardManager.retrieveUserById(createdUserId).complete();
                    } catch (ErrorResponseException e) {
                        if (e.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
                            userById = null;
                        } else {
                            throw e;
                        }
                    }
                    createdUser = userById != null ? userById.getName() : playlist.getCreatedUser();
                }
                String htmlString = String.format(html, playlist.getName(), playlist.getName(), Util.normalizeMillis(playlist.getDuration()), createdUser, playlist.getSize(), getList(playlist));
                byte[] bytes = htmlString.getBytes();
                exchange.sendResponseHeaders(200, bytes.length);
                OutputStream os = exchange.getResponseBody();
                os.write(bytes);
                os.close();
            } else {
                throw new InvalidRequestException("No playlist found");
            }
        } else {
            throw new InvalidRequestException("Insufficient request parameters");
        }
    } catch (InvalidRequestException e) {
        ServerUtil.handleError(exchange, e);
    } catch (Exception e) {
        ServerUtil.handleError(exchange, e);
        LoggerFactory.getLogger(getClass()).error("Error in HttpHandler", e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
Also used : Playlist(net.robinfriedli.aiode.entities.Playlist) User(net.dv8tion.jda.api.entities.User) OutputStream(java.io.OutputStream) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) IOException(java.io.IOException) Session(org.hibernate.Session)

Example 2 with InvalidRequestException

use of net.robinfriedli.aiode.exceptions.InvalidRequestException in project aiode by robinfriedli.

the class LoginHandler method handle.

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    String html = Files.readString(Path.of("html/login.html"));
    try {
        Map<String, String> parameterMap = ServerUtil.getParameters(httpExchange);
        String accessCode = parameterMap.get("code");
        String userId = parameterMap.get("state");
        String error = parameterMap.get("error");
        String response;
        if (accessCode != null) {
            User user;
            try {
                user = shardManager.retrieveUserById(userId).complete();
            } catch (ErrorResponseException e) {
                if (e.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
                    throw new IllegalArgumentException(String.format("Could not find user with id '%s'. " + "Please make sure the login link is valid and the bot is still a member of your guild.", userId));
                }
                throw e;
            }
            if (user == null) {
                throw new InvalidRequestException(String.format("No user found for id '%s'", userId));
            }
            CompletableFuture<Login> pendingLogin = loginManager.getPendingLogin(user);
            createLogin(accessCode, user, pendingLogin);
            response = String.format(html, "Welcome, " + user.getName());
        } else if (error != null) {
            response = String.format(html, "<span style=\"color: red\">Error:</span> " + error);
        } else {
            throw new InvalidRequestException("Missing parameter code or error");
        }
        httpExchange.sendResponseHeaders(200, response.getBytes().length);
        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    } catch (InvalidRequestException e) {
        ServerUtil.handleError(httpExchange, e);
    } catch (Exception e) {
        ServerUtil.handleError(httpExchange, e);
        LoggerFactory.getLogger(getClass()).error("Error in HttpHandler", e);
    }
}
Also used : User(net.dv8tion.jda.api.entities.User) OutputStream(java.io.OutputStream) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) ParseException(org.apache.hc.core5.http.ParseException) SpotifyWebApiException(se.michaelthelin.spotify.exceptions.SpotifyWebApiException) IOException(java.io.IOException)

Example 3 with InvalidRequestException

use of net.robinfriedli.aiode.exceptions.InvalidRequestException in project aiode by robinfriedli.

the class QueueViewHandler method handle.

@Override
public void handle(HttpExchange exchange) throws IOException {
    try {
        String html = Files.readString(Path.of("html/queue_view.html"));
        Map<String, String> parameterMap = ServerUtil.getParameters(exchange);
        String guildId = parameterMap.get("guildId");
        if (guildId != null) {
            Guild guild = shardManager.getGuildById(guildId);
            if (guild != null) {
                AudioPlayback playback = audioManager.getPlaybackForGuild(guild);
                AudioQueue queue = playback.getAudioQueue();
                String content;
                if (!queue.isEmpty()) {
                    int position = queue.getPosition();
                    List<Playable> previous = queue.listPrevious(position);
                    List<Playable> next = queue.listNext(queue.getTracks().size() - position);
                    StringBuilder listBuilder = new StringBuilder();
                    if (!previous.isEmpty()) {
                        if (previous.size() > 20) {
                            listBuilder.append("<a href=\"#current\">Jump to current track</a>").append(System.lineSeparator());
                        }
                        appendList(listBuilder, previous, "Previous");
                    }
                    listBuilder.append("<div id=\"current\">").append(System.lineSeparator());
                    appendList(listBuilder, Collections.singletonList(queue.getCurrent()), "Current");
                    listBuilder.append("</div>").append(System.lineSeparator());
                    if (!next.isEmpty()) {
                        appendList(listBuilder, next, "Next");
                    }
                    content = listBuilder.toString();
                } else {
                    content = "Queue is empty";
                }
                String response = String.format(html, boolToString(playback.isPaused()), boolToString(playback.isShuffle()), boolToString(playback.isRepeatAll()), boolToString(playback.isRepeatOne()), content);
                byte[] bytes = response.getBytes();
                exchange.sendResponseHeaders(200, bytes.length);
                OutputStream outputStream = exchange.getResponseBody();
                outputStream.write(bytes);
                outputStream.close();
            } else {
                throw new InvalidRequestException("Guild " + guildId + " not found");
            }
        } else {
            throw new InvalidRequestException("No guild provided");
        }
    } catch (InvalidRequestException e) {
        ServerUtil.handleError(exchange, e);
    } catch (Exception e) {
        ServerUtil.handleError(exchange, e);
        LoggerFactory.getLogger(getClass()).error("Error in HttpHandler", e);
    }
}
Also used : AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) OutputStream(java.io.OutputStream) Guild(net.dv8tion.jda.api.entities.Guild) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) IOException(java.io.IOException) Playable(net.robinfriedli.aiode.audio.Playable) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) AudioQueue(net.robinfriedli.aiode.audio.AudioQueue)

Aggregations

IOException (java.io.IOException)3 OutputStream (java.io.OutputStream)3 InvalidRequestException (net.robinfriedli.aiode.exceptions.InvalidRequestException)3 User (net.dv8tion.jda.api.entities.User)2 ErrorResponseException (net.dv8tion.jda.api.exceptions.ErrorResponseException)2 Guild (net.dv8tion.jda.api.entities.Guild)1 AudioPlayback (net.robinfriedli.aiode.audio.AudioPlayback)1 AudioQueue (net.robinfriedli.aiode.audio.AudioQueue)1 Playable (net.robinfriedli.aiode.audio.Playable)1 Playlist (net.robinfriedli.aiode.entities.Playlist)1 ParseException (org.apache.hc.core5.http.ParseException)1 Session (org.hibernate.Session)1 SpotifyWebApiException (se.michaelthelin.spotify.exceptions.SpotifyWebApiException)1