Search in sources :

Example 36 with FriendlyException

use of com.sedmelluq.discord.lavaplayer.tools.FriendlyException in project FredBoat by Frederikam.

the class PlaylistImportSourceManager method loadItem.

@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference ar) {
    String[] parsed = parse(ar.identifier);
    if (parsed == null)
        return null;
    String serviceName = parsed[0];
    String pasteId = parsed[1];
    if (pasteId == null || "".equals(pasteId) || !PasteServiceConstants.PASTE_SERVICE_URLS.containsKey(serviceName)) {
        return null;
    }
    List<String> trackIds = loadAndParseTrackIds(serviceName, pasteId);
    PasteServiceAudioResultHandler handler = new PasteServiceAudioResultHandler();
    Future<Void> lastFuture = null;
    for (String id : trackIds) {
        lastFuture = audioPlayerManager.loadItemOrdered(handler, id, handler);
    }
    if (lastFuture == null) {
        return null;
    }
    try {
        lastFuture.get();
    } catch (InterruptedException | ExecutionException ex) {
        throw new FriendlyException("Failed loading playlist item", FriendlyException.Severity.FAULT, ex);
    }
    return new BasicAudioPlaylist(pasteId, handler.getLoadedTracks(), null, false);
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Example 37 with FriendlyException

use of com.sedmelluq.discord.lavaplayer.tools.FriendlyException in project SkyBot by duncte123.

the class AudioUtils method loadAndPlay.

/**
 * Loads a track and plays it if the bot isn't playing
 *
 * @param mng         The {@link GuildMusicManager MusicManager} for the guild
 * @param channel     The {@link net.dv8tion.jda.core.entities.MessageChannel channel} that the bot needs to send the messages to
 * @param trackUrlRaw The url from the track to play
 * @param addPlayList If the url is a playlist
 */
public void loadAndPlay(GuildMusicManager mng, final TextChannel channel, final String trackUrlRaw, final boolean addPlayList) {
    final String trackUrl;
    // Strip <>'s that prevent discord from embedding link resources
    if (trackUrlRaw.startsWith("<") && trackUrlRaw.endsWith(">")) {
        trackUrl = trackUrlRaw.substring(1, trackUrlRaw.length() - 1);
    } else {
        trackUrl = trackUrlRaw;
    }
    playerManager.loadItemOrdered(mng, trackUrl, new AudioLoadResultHandler() {

        @Override
        public void trackLoaded(AudioTrack track) {
            String title = track.getInfo().title;
            if (track.getInfo().isStream) {
                Optional<RadioStream> stream = ((RadioCommand) AirUtils.COMMAND_MANAGER.getCommand("radio")).getRadioStreams().stream().filter(s -> s.getUrl().equals(track.getInfo().uri)).findFirst();
                if (stream.isPresent())
                    title = stream.get().getName();
            }
            String msg = "Adding to queue: " + title;
            if (mng.player.getPlayingTrack() == null) {
                msg += "\nand the Player has started playing;";
            }
            mng.scheduler.queue(track);
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, msg));
        }

        @Override
        public void playlistLoaded(AudioPlaylist playlist) {
            AudioTrack firstTrack = playlist.getSelectedTrack();
            List<AudioTrack> tracks = playlist.getTracks();
            if (tracks.size() == 0) {
                MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Error: This playlist is empty."));
                return;
            } else if (firstTrack == null) {
                firstTrack = playlist.getTracks().get(0);
            }
            String msg;
            if (addPlayList) {
                msg = "Adding **" + playlist.getTracks().size() + "** tracks to queue from playlist: " + playlist.getName();
                if (mng.player.getPlayingTrack() == null) {
                    msg += "\nand the Player has started playing;";
                }
                tracks.forEach(mng.scheduler::queue);
            } else {
                msg = "Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")";
                if (mng.player.getPlayingTrack() == null) {
                    msg += "\nand the Player has started playing;";
                }
                mng.scheduler.queue(firstTrack);
            }
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, msg));
        }

        @Override
        public void noMatches() {
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Nothing found by _" + trackUrl + "_"));
        }

        @Override
        public void loadFailed(FriendlyException exception) {
            MessageUtils.sendEmbed(channel, EmbedUtils.embedField(embedTitle, "Could not play: " + exception.getMessage() + "\nIf this happens often try another link or join our [support guild](https://discord.gg/NKM9Xtk) for more!"));
        }
    });
}
Also used : AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) RadioCommand(ml.duncte123.skybot.commands.music.RadioCommand) Optional(java.util.Optional) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) List(java.util.List) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Example 38 with FriendlyException

use of com.sedmelluq.discord.lavaplayer.tools.FriendlyException in project lavaplayer by sedmelluq.

the class YoutubeAudioSourceManager method loadTrackBaseInfoFromEmbedPage.

private JsonBrowser loadTrackBaseInfoFromEmbedPage(HttpInterface httpInterface, String videoId) throws Exception {
    try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com/embed/" + videoId))) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new IOException("Invalid status code for embed video page response: " + statusCode);
        }
        String html = IOUtils.toString(response.getEntity().getContent(), Charset.forName(CHARSET));
        String configJson = DataFormatTools.extractBetween(html, "'PLAYER_CONFIG': ", ",'EXPERIMENT_FLAGS'");
        if (configJson != null) {
            return JsonBrowser.parse(configJson);
        }
    }
    throw new FriendlyException("Track information is unavailable.", SUSPICIOUS, new IllegalStateException("Expected player config is not present in embed page."));
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Example 39 with FriendlyException

use of com.sedmelluq.discord.lavaplayer.tools.FriendlyException in project lavaplayer by sedmelluq.

the class YoutubeAudioSourceManager method buildPlaylist.

private AudioPlaylist buildPlaylist(HttpInterface httpInterface, Document document, String selectedVideoId) throws IOException {
    boolean isAccessible = !document.select("#pl-header").isEmpty();
    if (!isAccessible) {
        if (selectedVideoId != null) {
            return null;
        } else {
            throw new FriendlyException("The playlist is private.", COMMON, null);
        }
    }
    Element container = document.select("#pl-header").first().parent();
    String playlistName = container.select(".pl-header-title").first().text();
    List<AudioTrack> tracks = new ArrayList<>();
    String loadMoreUrl = extractPlaylistTracks(container, container, tracks);
    int loadCount = 0;
    int pageCount = playlistPageCount;
    // Also load the next pages, each result gives us a JSON with separate values for list html and next page loader html
    while (loadMoreUrl != null && ++loadCount < pageCount) {
        try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com" + loadMoreUrl))) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("Invalid status code for playlist response: " + statusCode);
            }
            JsonBrowser json = JsonBrowser.parse(response.getEntity().getContent());
            String html = json.get("content_html").text();
            Element videoContainer = Jsoup.parse("<table>" + html + "</table>", "");
            String moreHtml = json.get("load_more_widget_html").text();
            Element moreContainer = moreHtml != null ? Jsoup.parse(moreHtml) : null;
            loadMoreUrl = extractPlaylistTracks(videoContainer, moreContainer, tracks);
        }
    }
    return new BasicAudioPlaylist(playlistName, tracks, findSelectedTrack(tracks, selectedVideoId), false);
}
Also used : BasicAudioPlaylist(com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist) Element(org.jsoup.nodes.Element) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) IOException(java.io.IOException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) JsonBrowser(com.sedmelluq.discord.lavaplayer.tools.JsonBrowser)

Example 40 with FriendlyException

use of com.sedmelluq.discord.lavaplayer.tools.FriendlyException in project lavaplayer by sedmelluq.

the class YoutubeAudioTrack method loadTrackFormats.

private List<YoutubeTrackFormat> loadTrackFormats(JsonBrowser info, HttpInterface httpInterface, String playerScript) throws Exception {
    JsonBrowser args = info.safeGet("args");
    String adaptiveFormats = args.safeGet("adaptive_fmts").text();
    if (adaptiveFormats != null) {
        return loadTrackFormatsFromAdaptive(adaptiveFormats);
    }
    String dashUrl = args.safeGet("dashmpd").text();
    if (dashUrl != null) {
        return loadTrackFormatsFromDash(dashUrl, httpInterface, playerScript);
    }
    String formatStreamMap = args.safeGet("url_encoded_fmt_stream_map").text();
    if (formatStreamMap != null) {
        return loadTrackFormatsFromFormatStreamMap(formatStreamMap);
    }
    throw new FriendlyException("Unable to play this YouTube track.", SUSPICIOUS, new IllegalStateException("No adaptive formats, no dash, no stream map."));
}
Also used : JsonBrowser(com.sedmelluq.discord.lavaplayer.tools.JsonBrowser) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Aggregations

FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)62 IOException (java.io.IOException)23 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)18 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 AudioLoadResultHandler (com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler)12 JsonBrowser (com.sedmelluq.discord.lavaplayer.tools.JsonBrowser)12 AudioPlaylist (com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)12 ArrayList (java.util.ArrayList)10 HttpGet (org.apache.http.client.methods.HttpGet)10 List (java.util.List)7 HttpInterface (com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface)6 BasicAudioPlaylist (com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 MediaContainerHints (com.sedmelluq.discord.lavaplayer.container.MediaContainerHints)3 PersistentHttpStream (com.sedmelluq.discord.lavaplayer.tools.io.PersistentHttpStream)3 AudioReference (com.sedmelluq.discord.lavaplayer.track.AudioReference)3 AudioTrackInfo (com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo)3 Document (org.jsoup.nodes.Document)3 Track (com.arsenarsen.lavaplayerbridge.player.Track)2