Search in sources :

Example 71 with ParseException

use of org.apache.hc.core5.http.ParseException in project ascent_bot by FeroniK.

the class SpotifyAudioSource method getPlaylist.

public void getPlaylist(CommandContext ctx, String url) {
    final Matcher res = SPOTIFY_PLAYLIST_REGEX.matcher(url);
    if (!res.matches()) {
        return;
    }
    try {
        GuildMusicManager musicManager = PlayerManager.getInstance().getMusicManager(ctx.getGuild());
        final Playlist spotifyPlaylist = this.spi.getPlaylist(res.group(res.groupCount())).build().execute();
        List<PlaylistTrack> playlistTracks = List.of(spotifyPlaylist.getTracks().getItems());
        if (playlistTracks.isEmpty()) {
            return;
        }
        final int originalSize = playlistTracks.size();
        if (originalSize > musicManager.scheduler.MAX_QUEUE_SIZE) {
            playlistTracks = playlistTracks.subList(0, musicManager.scheduler.MAX_QUEUE_SIZE);
        }
        final List<Track> finalPlaylist = new ArrayList<>();
        for (final PlaylistTrack playlistTrack : playlistTracks) {
            if (playlistTrack.getIsLocal()) {
                continue;
            }
            final IPlaylistItem item = playlistTrack.getTrack();
            if (item instanceof Track) {
                Track track = (Track) item;
                finalPlaylist.add(track);
            }
        }
        ctx.getChannel().sendMessageEmbeds(Embeds.createBuilder(null, "Spotify Playlist Loaded : Adding " + finalPlaylist.size() + " Tracks to the queue", null, null, null).build()).queue();
        for (Track track : finalPlaylist) {
            final String query = "ytsearch:" + track.getName() + " " + track.getArtists()[0].getName();
            PlayerManager.getInstance().audioPlayerManager.loadItemOrdered(musicManager, query, new AudioLoadResultHandler() {

                @Override
                public void trackLoaded(AudioTrack track) {
                }

                @Override
                public void playlistLoaded(AudioPlaylist playlist) {
                    boolean empty = playlist.getTracks().isEmpty();
                    if (empty) {
                        return;
                    }
                    AudioTrack audioTrack = playlist.getTracks().get(0);
                    audioTrack.setUserData(ctx.getAuthor().getIdLong());
                    musicManager.scheduler.queue(audioTrack);
                }

                @Override
                public void noMatches() {
                }

                @Override
                public void loadFailed(FriendlyException exception) {
                }
            });
        }
    } catch (IOException | SpotifyWebApiException | ParseException e) {
        e.printStackTrace();
    }
}
Also used : AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) Matcher(java.util.regex.Matcher) GuildMusicManager(me.fero.ascent.lavaplayer.GuildMusicManager) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SpotifyWebApiException(se.michaelthelin.spotify.exceptions.SpotifyWebApiException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) IPlaylistItem(se.michaelthelin.spotify.model_objects.IPlaylistItem) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) ParseException(org.apache.hc.core5.http.ParseException) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)

Example 72 with ParseException

use of org.apache.hc.core5.http.ParseException in project aiode by robinfriedli.

the class SetRedirectedSpotifyTrackNameTask method perform.

@Override
public void perform(@Nullable JDA shard) throws Exception {
    ClientCredentials clientCredentials = spotifyApi.clientCredentials().build().execute();
    spotifyApi.setAccessToken(clientCredentials.getAccessToken());
    File file = new File("src/main/resources/playlists.xml");
    if (file.exists()) {
        try (Context context = jxpBackend.getContext(file)) {
            context.invoke(() -> {
                try {
                    migrate(context, spotifyApi);
                } catch (IOException | SpotifyWebApiException | ParseException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    spotifyApi.setAccessToken(null);
}
Also used : Context(net.robinfriedli.jxp.persist.Context) IOException(java.io.IOException) ParseException(org.apache.hc.core5.http.ParseException) ClientCredentials(se.michaelthelin.spotify.model_objects.credentials.ClientCredentials) File(java.io.File) SpotifyWebApiException(se.michaelthelin.spotify.exceptions.SpotifyWebApiException)

Example 73 with ParseException

use of org.apache.hc.core5.http.ParseException in project aiode by robinfriedli.

the class PlayableFactory method createPlayable.

/**
 * Create a single playable for any url. If the url is either an open.spotify or YouTube URL this extracts the ID
 * and uses the familiar methods to load the Playables, otherwise this method uses the {@link AudioTrackLoader}
 * to load the {@link AudioTrack}s using lavaplayer and wraps them in {@link UrlPlayable}s
 */
@Nullable
public Playable createPlayable(String url, SpotifyApi spotifyApi, boolean redirectSpotify) throws IOException {
    URI uri;
    try {
        uri = URI.create(url);
    } catch (IllegalArgumentException e) {
        throw new InvalidCommandException("'" + url + "' is not a valid URL");
    }
    if (uri.getHost().contains("youtube.com")) {
        Map<String, String> parameterMap = getParameterMap(uri);
        String videoId = parameterMap.get("v");
        if (videoId != null) {
            return youTubeService.getVideoForId(videoId);
        } else {
            throw new IllegalArgumentException("Detected YouTube URL but no video id provided");
        }
    } else if (uri.getHost().equals("youtu.be")) {
        String[] parts = uri.getPath().split("/");
        return youTubeService.requireVideoForId(parts[parts.length - 1]);
    } else if (uri.getHost().equals("open.spotify.com")) {
        StringList pathFragments = StringList.createWithRegex(uri.getPath(), "/");
        SpotifyTrackKind kind;
        String trackId;
        if (pathFragments.contains("track")) {
            trackId = pathFragments.tryGet(pathFragments.indexOf("track") + 1);
            kind = SpotifyTrackKind.TRACK;
        } else if (pathFragments.contains("episode")) {
            trackId = pathFragments.tryGet(pathFragments.indexOf("episode") + 1);
            kind = SpotifyTrackKind.EPISODE;
        } else {
            throw new IllegalArgumentException("Detected Spotify URL but no track id provided");
        }
        if (trackId == null) {
            throw new InvalidCommandException("No track id provided");
        }
        try {
            String accessToken = spotifyApi.clientCredentials().build().execute().getAccessToken();
            spotifyApi.setAccessToken(accessToken);
            if (kind == SpotifyTrackKind.TRACK) {
                Track track = spotifyService.getTrack(trackId);
                return createPlayable(redirectSpotify, track);
            } else // noinspection ConstantConditions
            if (kind == SpotifyTrackKind.EPISODE) {
                Episode episode = spotifyService.getEpisode(trackId);
                return createPlayable(redirectSpotify, episode);
            } else {
                throw new UnsupportedOperationException("unsupported open.spotify URL kind: " + kind);
            }
        } catch (IOException | SpotifyWebApiException | ParseException e) {
            throw new RuntimeException("Exception during Spotify request", e);
        } finally {
            spotifyApi.setAccessToken(null);
        }
    } else {
        AudioItem audioItem = audioTrackLoader.loadByIdentifier(uri.toString());
        if (audioItem instanceof AudioTrack) {
            return new UrlPlayable((AudioTrack) audioItem);
        } else if (audioItem != null) {
            throw new IllegalArgumentException("Loading provided url did not result in an AudioTrack but " + audioItem.getClass().toString());
        } else {
            return null;
        }
    }
}
Also used : StringList(net.robinfriedli.stringlist.StringList) IOException(java.io.IOException) URI(java.net.URI) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) SpotifyWebApiException(se.michaelthelin.spotify.exceptions.SpotifyWebApiException) Episode(se.michaelthelin.spotify.model_objects.specification.Episode) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) SpotifyTrackKind(net.robinfriedli.aiode.audio.spotify.SpotifyTrackKind) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) ParseException(org.apache.hc.core5.http.ParseException) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Track(se.michaelthelin.spotify.model_objects.specification.Track) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) UrlTrack(net.robinfriedli.aiode.entities.UrlTrack) Nullable(javax.annotation.Nullable)

Aggregations

ParseException (org.apache.hc.core5.http.ParseException)62 IOException (java.io.IOException)54 SpotifyWebApiException (se.michaelthelin.spotify.exceptions.SpotifyWebApiException)33 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)24 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)13 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)12 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)11 HttpEntity (org.apache.hc.core5.http.HttpEntity)10 HashMap (java.util.HashMap)8 Map (java.util.Map)6 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)6 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)6 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)5 ArrayList (java.util.ArrayList)5 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)5 Matcher (java.util.regex.Matcher)4 UrlEncodedFormEntity (org.apache.hc.client5.http.entity.UrlEncodedFormEntity)4 AuthorizationCodeCredentials (se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials)4 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)3 List (java.util.List)3