com.sedmelluq.discord.lavaplayer.track.AudioPlaylist Java Examples

The following examples show how to use com.sedmelluq.discord.lavaplayer.track.AudioPlaylist. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist audioPlaylist) {
    // SoundCloud returns an empty playlist when no results where found
    if (audioPlaylist.getTracks().isEmpty()) {
        LOGGER.debug("{Guild ID: {}} Empty playlist: {}", this.guildId.asLong(), audioPlaylist.hashCode());
        this.onNoMatches();
    }
    // If a track is specifically selected
    else if (audioPlaylist.getSelectedTrack() != null) {
        LOGGER.debug("{Guild ID: {}} Playlist loaded, track selected: {}", this.guildId.asLong(), audioPlaylist.hashCode());
        this.trackLoaded(audioPlaylist.getSelectedTrack());
    }
    // The user is searching something
    else if (audioPlaylist.isSearchResult()) {
        LOGGER.debug("{Guild ID: {}} Playlist loaded, search results: {}", this.guildId.asLong(), audioPlaylist.hashCode());
        this.onSearchResult(audioPlaylist);
    }
    // The user loads a full playlist
    else {
        LOGGER.debug("{Guild ID: {}} Playlist loaded, full playlist: {}", this.guildId.asLong(), audioPlaylist.hashCode());
        this.onPlaylistLoaded(audioPlaylist);
    }
}
 
Example #2
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private void onSearchResult(AudioPlaylist playlist) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .flatMapMany(guildMusic -> {
                this.resultTracks = playlist.getTracks()
                        .subList(0, Math.min(Config.MUSIC_SEARCHES, playlist.getTracks().size()));

                guildMusic.setDjId(this.djId);
                guildMusic.setWaitingForChoice(true);

                return guildMusic.getGateway()
                        .getUserById(guildMusic.getDjId())
                        .map(User::getAvatarUrl)
                        .flatMap(avatarUrl -> this.getPlaylistEmbed(playlist, avatarUrl))
                        .flatMap(embed -> guildMusic.getMessageChannel()
                                .flatMap(channel -> DiscordUtils.sendMessage(embed, channel)))
                        .flatMapMany(ignored ->
                                AudioLoadResultInputs.create(guildMusic.getGateway(), Duration.ofSeconds(30),
                                        guildMusic.getMessageChannelId(), this)
                                        .waitForInputs()
                                        .then(Mono.fromRunnable(() -> guildMusic.setWaitingForChoice(false))));
            })
            .then(this.terminate())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #3
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private void onPlaylistLoaded(AudioPlaylist playlist) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .zipWith(DatabaseManager.getPremium().isPremium(this.guildId, this.djId))
            .flatMap(TupleUtils.function((guildMusic, isPremium) -> {
                final TrackScheduler trackScheduler = guildMusic.getTrackScheduler();
                final StringBuilder strBuilder = new StringBuilder();

                int musicsAdded = 0;
                for (final AudioTrack track : playlist.getTracks()) {
                    trackScheduler.startOrQueue(track, this.insertFirst);
                    musicsAdded++;
                    // The playlist limit is reached and the user / guild is not premium
                    if (trackScheduler.getPlaylist().size() >= Config.PLAYLIST_SIZE - 1 && !isPremium) {
                        strBuilder.append(ShadbotUtils.PLAYLIST_LIMIT_REACHED + "\n");
                        break;
                    }
                }

                strBuilder.append(String.format(Emoji.MUSICAL_NOTE + " %d musics have been added to the playlist.", musicsAdded));
                return guildMusic.getMessageChannel()
                        .flatMap(channel -> DiscordUtils.sendMessage(strBuilder.toString(), channel));
            }))
            .then(this.terminate())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #4
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private Mono<Consumer<EmbedCreateSpec>> getPlaylistEmbed(AudioPlaylist playlist, String avatarUrl) {
    final String choices = FormatUtils.numberedList(Config.MUSIC_SEARCHES, playlist.getTracks().size(),
            count -> {
                final AudioTrackInfo info = playlist.getTracks().get(count - 1).getInfo();
                return String.format("\t**%d.** [%s](%s)", count, FormatUtils.trackName(info), info.uri);
            });

    final String playlistName = StringUtils.abbreviate(playlist.getName(), MAX_PLAYLIST_NAME_LENGTH);
    return DatabaseManager.getGuilds()
            .getDBGuild(this.guildId)
            .map(DBGuild::getSettings)
            .map(Settings::getPrefix)
            .map(prefix -> ShadbotUtils.getDefaultEmbed()
                    .andThen(embed -> embed.setAuthor(playlistName, null, avatarUrl)
                            .setThumbnail("https://i.imgur.com/IG3Hj2W.png")
                            .setDescription("**Select a music by typing the corresponding number.**"
                                    + "\nYou can choose several musics by separating them with a comma."
                                    + "\nExample: 1,3,4"
                                    + "\n\n" + choices)
                            .setFooter(String.format("Use %scancel to cancel the selection (Automatically " +
                                    "canceled in %ds).", prefix, Config.MUSIC_CHOICE_DURATION), null)));
}
 
Example #5
Source File: AudioLoader.java    From Lavalink with MIT License 6 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist audioPlaylist) {
    log.info("Loaded playlist " + audioPlaylist.getName());

    String playlistName = null;
    Integer selectedTrack = null;
    if (!audioPlaylist.isSearchResult()) {
        playlistName = audioPlaylist.getName();
        selectedTrack = audioPlaylist.getTracks().indexOf(audioPlaylist.getSelectedTrack());
    }

    ResultStatus status = audioPlaylist.isSearchResult() ? ResultStatus.SEARCH_RESULT : ResultStatus.PLAYLIST_LOADED;
    List<AudioTrack> loadedItems = audioPlaylist.getTracks();

    this.loadResult.complete(new LoadResult(status, loadedItems, playlistName, selectedTrack));
}
 
Example #6
Source File: YoutubeApiPlaylistLoader.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId, Function<AudioTrackInfo, AudioTrack> trackFactory) {
    try {
        final YoutubePlaylistMetadata firstPage = getPlaylistPageById(playlistId, this.apiKey, null, true);

        if (firstPage == null) {
            throw new FriendlyException("This playlist does not exist", COMMON, null);
        }

        return buildPlaylist(firstPage, playlistId, selectedVideoId, trackFactory);
    }
    catch (IOException e) {
        Sentry.capture(e);

        throw ExceptionTools.wrapUnfriendlyExceptions(e);
    }
}
 
Example #7
Source File: YoutubeApiPlaylistLoader.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private AudioPlaylist buildPlaylist(YoutubePlaylistMetadata firstPage, String playlistId, String selectedVideoId,
                                    Function<AudioTrackInfo, AudioTrack> trackFactory) throws IOException {
    final List<AudioTrack> convertedTracks = new ArrayList<>();

    firstPage.getTracks()
        .stream()
        .map(trackFactory)
        .forEach(convertedTracks::add);

    String nextPageKey = firstPage.getNextPageKey();
    int loadCount = 0;
    final int pageCount = playlistPageCount;

    while (nextPageKey != null && ++loadCount < pageCount) {
        nextPageKey = fetchNextPage(nextPageKey, playlistId, trackFactory, convertedTracks);
    }

    return new BasicAudioPlaylist(
        firstPage.getTitle(),
        convertedTracks,
        getSelectedTrack(selectedVideoId, convertedTracks),
        false
    );
}
 
Example #8
Source File: DefaultYoutubePlaylistLoader.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId,
                          Function<AudioTrackInfo, AudioTrack> trackFactory) {

  HttpGet request = new HttpGet(getPlaylistUrl(playlistId) + "&pbj=1&hl=en");

  try (CloseableHttpResponse response = httpInterface.execute(request)) {
    int statusCode = response.getStatusLine().getStatusCode();
    if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code for playlist response: " + statusCode);
    }

    JsonBrowser json = JsonBrowser.parse(response.getEntity().getContent());

    return buildPlaylist(httpInterface, json, selectedVideoId, trackFactory);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #9
Source File: AudioPlayerLoadResultHandler.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist audioPlaylist) {
	for (Iterator<AudioTrack> iterator = audioPlaylist.getTracks().iterator(); iterator.hasNext();) {
		AudioTrack audioTrack = iterator.next();
		if (audioTrack == null) {
			continue;
		}
		
		Audio audio = new Audio(getTextChannel(), getMember(), audioTrack);
		DiscordBot.getInstance().getDiscord().getAudioQueue().getQueue().add(audio);
		if (DiscordBot.getInstance().getDiscord().getAudioPlayer().getPlayingTrack() == null) {
			DiscordBot.getInstance().getDiscord().getAudioQueue().playNext();
		} else {
			LogHelper.debug("'" + audio.getAudioTrack().getInfo().title + "' Has been added to the queue.");
		}
		audio = null;
	}
	LogHelper.debug(audioPlaylist.getTracks().size() + " Songs have been added to the queue.");
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.SUCCESS);
	embedBuilder.setTitle(audioPlaylist.getTracks().size() + " Songs have been added to the queue.", null);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #10
Source File: DefaultSoundCloudPlaylistLoader.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
protected AudioPlaylist loadFromSet(
    HttpInterfaceManager httpInterfaceManager,
    String playlistWebUrl,
    Function<AudioTrackInfo, AudioTrack> trackFactory
) {
  try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) {
    JsonBrowser rootData = htmlDataLoader.load(httpInterface, playlistWebUrl);
    JsonBrowser playlistData = dataReader.findPlaylistData(rootData);

    return new BasicAudioPlaylist(
        dataReader.readPlaylistName(playlistData),
        loadPlaylistTracks(httpInterface, playlistData, trackFactory),
        null,
        false
    );
  } catch (IOException e) {
    throw new FriendlyException("Loading playlist from SoundCloud failed.", SUSPICIOUS, e);
  }
}
 
Example #11
Source File: DefaultAudioPlayerManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private AudioItem checkSourcesForItemOnce(AudioReference reference, AudioLoadResultHandler resultHandler, boolean[] reported) {
  for (AudioSourceManager sourceManager : sourceManagers) {
    if (reference.containerDescriptor != null && !(sourceManager instanceof ProbingAudioSourceManager)) {
      continue;
    }

    AudioItem item = sourceManager.loadItem(this, reference);

    if (item != null) {
      if (item instanceof AudioTrack) {
        log.debug("Loaded a track with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
        reported[0] = true;
        resultHandler.trackLoaded((AudioTrack) item);
      } else if (item instanceof AudioPlaylist) {
        log.debug("Loaded a playlist with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
        reported[0] = true;
        resultHandler.playlistLoaded((AudioPlaylist) item);
      }
      return item;
    }
  }

  return null;
}
 
Example #12
Source File: FunctionalResultHandler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Refer to {@link AudioLoadResultHandler} methods for details on when each method is called.
 *
 * @param trackConsumer Consumer for single track result
 * @param playlistConsumer Consumer for playlist result
 * @param emptyResultHandler Empty result handler
 * @param exceptionConsumer Consumer for an exception when loading the item fails
 */
public FunctionalResultHandler(Consumer<AudioTrack> trackConsumer, Consumer<AudioPlaylist> playlistConsumer,
                               Runnable emptyResultHandler, Consumer<FriendlyException> exceptionConsumer) {

  this.trackConsumer = trackConsumer;
  this.playlistConsumer = playlistConsumer;
  this.emptyResultHandler = emptyResultHandler;
  this.exceptionConsumer = exceptionConsumer;
}
 
Example #13
Source File: AudioLoader.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private void onSearch(AudioPlaylist playlist) {
    List<AudioTrack> list = playlist.getTracks();
    DiscordUtils.selectList(event, list.subList(0, Math.min(5, list.size())),
            track -> String.format("**[%s](%s)** (%s)", track.getInfo().title, track.getInfo().uri, Utils.getDurationMinutes(track.getInfo().length)),
            s -> new EmbedBuilder().setColor(Color.CYAN).setAuthor(language.get("commands.music_general.loader.selection_text"), "https://i.imgur.com/sFDpUZy.png")
                    .setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png")
                    .setDescription(s)
                    .setFooter(language.get("commands.music_general.loader.timeout_text"), null).build(),
            selected -> loadSingle(selected, false)
    );

    Metrics.TRACK_EVENTS.labels("tracks_search").inc();
}
 
Example #14
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private void loadAndPlay(final TextChannel channel, final String trackUrl) {
  GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild());

  playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
    @Override
    public void trackLoaded(AudioTrack track) {
      channel.sendMessage("Adding to queue " + track.getInfo().title).queue();

      play(channel.getGuild(), musicManager, track);
    }

    @Override
    public void playlistLoaded(AudioPlaylist playlist) {
      AudioTrack firstTrack = playlist.getSelectedTrack();

      if (firstTrack == null) {
        firstTrack = playlist.getTracks().get(0);
      }

      channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue();

      play(channel.getGuild(), musicManager, firstTrack);
    }

    @Override
    public void noMatches() {
      channel.sendMessage("Nothing found by " + trackUrl).queue();
    }

    @Override
    public void loadFailed(FriendlyException exception) {
      channel.sendMessage("Could not play: " + exception.getMessage()).queue();
    }
  });
}
 
Example #15
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private void loadAndPlay(TextChannel channel, final String trackUrl) {
  GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild().block());

  playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
    @Override
    public void trackLoaded(AudioTrack track) {
      sendMessageToChannel(channel, "Adding to queue " + track.getInfo().title);

      play(channel.getGuild().block(), musicManager, track);
    }

    @Override
    public void playlistLoaded(AudioPlaylist playlist) {
      AudioTrack firstTrack = playlist.getSelectedTrack();

      if (firstTrack == null) {
        firstTrack = playlist.getTracks().get(0);
      }

      sendMessageToChannel(channel, "Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")");

      play(channel.getGuild().block(), musicManager, firstTrack);
    }

    @Override
    public void noMatches() {
      sendMessageToChannel(channel, "Nothing found by " + trackUrl);
    }

    @Override
    public void loadFailed(FriendlyException exception) {
      sendMessageToChannel(channel, "Could not play: " + exception.getMessage());
    }
  });
}
 
Example #16
Source File: DefaultSoundCloudPlaylistLoader.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioPlaylist load(
    String identifier,
    HttpInterfaceManager httpInterfaceManager,
    Function<AudioTrackInfo, AudioTrack> trackFactory
) {
  String url = SoundCloudHelper.nonMobileUrl(identifier);

  if (playlistUrlPattern.matcher(url).matches()) {
    return loadFromSet(httpInterfaceManager, url, trackFactory);
  } else {
    return null;
  }
}
 
Example #17
Source File: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private AudioItem checkSourcesForItemOnce(AudioReference reference, AudioLoadResultHandler resultHandler, boolean[] reported, boolean isPatron) {
    for (final AudioSourceManager sourceManager : sourceManagers.get()) {
        if (reference.containerDescriptor != null && !(sourceManager instanceof ProbingAudioSourceManager)) {
            continue;
        }

        final AudioItem item;

        if (sourceManager instanceof SpotifyAudioSourceManager) {
            item = ((SpotifyAudioSourceManager) sourceManager).loadItem(reference, isPatron);
        } else {
            item = sourceManager.loadItem(this, reference);
        }

        if (item != null) {
            if (item instanceof AudioTrack) {
                log.debug("Loaded a track with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
                reported[0] = true;
                resultHandler.trackLoaded((AudioTrack) item);
            } else if (item instanceof AudioPlaylist) {
                log.debug("Loaded a playlist with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
                reported[0] = true;
                resultHandler.playlistLoaded((AudioPlaylist) item);
            }
            return item;
        }
    }

    return null;
}
 
Example #18
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public void play(AudioPlaylist playlist, List<TrackRequest> requests) throws DiscordException {
    if (CollectionUtils.isEmpty(requests)) {
        return;
    }

    TrackRequest request = requests.get(0);
    Guild guild = discordService.getShardManager().getGuildById(request.getGuildId());
    if (guild == null) {
        return;
    }
    PlaybackInstance instance = getOrCreate(guild);

    boolean store = true;
    if (playlist instanceof StoredPlaylist) {
        StoredPlaylist storedPlaylist = (StoredPlaylist) playlist;
        if (isActive(guild)) {
            if (Objects.equals(storedPlaylist.getPlaylistId(), instance.getPlaylistId())) {
                throw new DiscordException("discord.command.audio.playlistInQueue");
            }
        } else if (storedPlaylist.getGuildId() == guild.getIdLong()) {
            instance.setPlaylistId(storedPlaylist.getPlaylistId());
            instance.setPlaylistUuid(storedPlaylist.getPlaylistUuid());
            store = false;
        }
    }

    if (store) {
        storedPlaylistService.storeToPlaylist(instance, requests);
    }

    play(request, instance);
    if (requests.size() > 1) {
        requests.subList(1, requests.size()).forEach(instance::offer);
    }
}
 
Example #19
Source File: Music.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
private void loadTrack(String identifier, Member author, Message msg) {


        Guild guild = author.getGuild();
        getPlayer(guild);

        msg.getTextChannel().sendTyping().queue();
        myManager.setFrameBufferDuration(5000);
        myManager.loadItemOrdered(guild, identifier, new AudioLoadResultHandler() {

            @Override
            public void trackLoaded(AudioTrack track) {

                getTrackManager(guild).queue(track, author);
            }

            @Override
            public void playlistLoaded(AudioPlaylist playlist) {
                if (playlist.getSelectedTrack() != null) {
                    trackLoaded(playlist.getSelectedTrack());
                } else if (playlist.isSearchResult()) {
                    trackLoaded(playlist.getTracks().get(0));
                } else {

                    for (int i = 0; i < Math.min(playlist.getTracks().size(), PLAYLIST_LIMIT); i++) {
                        getTrackManager(guild).queue(playlist.getTracks().get(i), author);
                    }
                }
            }

            @Override
            public void noMatches() {
            }

            @Override
            public void loadFailed(FriendlyException exception) {
            }
        });
    }
 
Example #20
Source File: YoutubeMixProvider.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
/**
 * Loads tracks from mix in parallel into a playlist entry.
 *
 * @param mixId ID of the mix
 * @param selectedVideoId Selected track, {@link AudioPlaylist#getSelectedTrack()} will return this.
 * @return Playlist of the tracks in the mix.
 */
public AudioPlaylist load(
    HttpInterface httpInterface,
    String mixId,
    String selectedVideoId,
    Function<AudioTrackInfo, AudioTrack> trackFactory
) {
  String playlistTitle = "YouTube mix";
  List<AudioTrack> tracks = new ArrayList<>();

  String mixUrl = "https://www.youtube.com/watch?v=" + selectedVideoId + "&list=" + mixId + "&pbj=1";

  try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(mixUrl))) {
    int statusCode = response.getStatusLine().getStatusCode();
    if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code for mix response: " + statusCode);
    }

    JsonBrowser body = JsonBrowser.parse(response.getEntity().getContent());
    JsonBrowser playlist = body.index(3).get("response")
            .get("contents")
            .get("twoColumnWatchNextResults")
            .get("playlist")
            .get("playlist");

    JsonBrowser title = playlist.get("title");

    if (!title.isNull()) {
      playlistTitle = title.text();
    }

    extractPlaylistTracks(playlist.get("contents"), tracks, trackFactory);
  } catch (IOException e) {
    throw new FriendlyException("Could not read mix page.", SUSPICIOUS, e);
  }

  if (tracks.isEmpty()) {
    throw new FriendlyException("Could not find tracks from mix.", SUSPICIOUS, null);
  }

  AudioTrack selectedTrack = findSelectedTrack(tracks, selectedVideoId);
  return new BasicAudioPlaylist(playlistTitle, tracks, selectedTrack, false);
}
 
Example #21
Source File: PlayerControl.java    From Yui with Apache License 2.0 4 votes vote down vote up
private void loadAndPlay(GuildMusicManager mng, final MessageChannel channel, String url, final boolean addPlaylist)
{
    final String trackUrl;

    //Strip <>'s that prevent discord from embedding link resources
    if (url.startsWith("<") && url.endsWith(">"))
        trackUrl = url.substring(1, url.length() - 1);
    else
        trackUrl = url;

    playerManager.loadItemOrdered(mng, trackUrl, new AudioLoadResultHandler()
    {
        @Override
        public void trackLoaded(AudioTrack track)
        {
            String msg = "Adding to queue: " + track.getInfo().title;
            if (mng.player.getPlayingTrack() == null)
                msg += "\nand the Player has started playing;";

            mng.scheduler.queue(track);
            channel.sendMessage(msg).queue();
        }

        @Override
        public void playlistLoaded(AudioPlaylist playlist)
        {
            AudioTrack firstTrack = playlist.getSelectedTrack();
            List<AudioTrack> tracks = playlist.getTracks();


            if (firstTrack == null) {
                firstTrack = playlist.getTracks().get(0);
            }

            if (addPlaylist)
            {
                channel.sendMessage("Adding **" + playlist.getTracks().size() +"** tracks to queue from playlist: " + playlist.getName()).queue();
                tracks.forEach(mng.scheduler::queue);
            }
            else
            {
                channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue();
                mng.scheduler.queue(firstTrack);
            }
        }

        @Override
        public void noMatches()
        {
            channel.sendMessage("Nothing found by " + trackUrl).queue();
        }

        @Override
        public void loadFailed(FriendlyException exception)
        {
            channel.sendMessage("Could not play: " + exception.getMessage()).queue();
        }
    });
}
 
Example #22
Source File: AudioLoader.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist playlist) {
    if (playlist.isSearchResult()) {
        if (!skipSelection) {
            onSearch(playlist);
        } else {
            loadSingle(playlist.getTracks().get(0), false);
        }

        return;
    }

    try {
        int i = 0;
        for (AudioTrack track : playlist.getTracks()) {
            DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
            DBUser user = MantaroData.db().getUser(event.getMember());
            GuildData guildData = dbGuild.getData();

            if (guildData.getMusicQueueSizeLimit() != null) {
                if (i < guildData.getMusicQueueSizeLimit()) {
                    loadSingle(track, true);
                } else {
                    event.getChannel().sendMessageFormat(language.get("commands.music_general.loader.over_limit"), EmoteReference.WARNING, guildData.getMusicQueueSizeLimit()).queue();
                    break;
                }
            } else {
                if (i > MAX_QUEUE_LENGTH && (!dbGuild.isPremium() && !user.isPremium())) {
                    event.getChannel().sendMessageFormat(language.get("commands.music_general.loader.over_limit"), EmoteReference.WARNING, MAX_QUEUE_LENGTH).queue();
                    break; //stop adding songs
                } else {
                    loadSingle(track, true);
                }
            }

            i++;
        }

        event.getChannel().sendMessageFormat(language.get("commands.music_general.loader.loaded_playlist"),
                EmoteReference.CORRECT, i, playlist.getName(), Utils.getDurationMinutes(playlist.getTracks().stream().mapToLong(temp -> temp.getInfo().length).sum())
        ).queue();
    } catch (Exception e) {
        SentryHelper.captureExceptionContext("Cannot load playlist. I guess something broke pretty hard. Please check", e, this.getClass(), "Music Loader");
    }
}
 
Example #23
Source File: ValidationService.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
public List<AudioTrack> filterPlaylist(AudioPlaylist playlist, Member requestedBy) throws ValidationException {
    MusicConfig config = musicConfigService.get(requestedBy.getGuild());
    Long queueLimit = config != null ? config.getQueueLimit() : null;
    Long durationLimit = config != null ? config.getDurationLimit() : null;
    Long duplicateLimit = config != null ? config.getDuplicateLimit() : null;
    PlaybackInstance instance = playerService.get(requestedBy.getGuild());

    if (config == null || !Boolean.TRUE.equals(config.getPlaylistEnabled())) {
        throw new ValidationException("discord.command.audio.queue.limits.playlists");
    }

    List<AudioTrack> tracks = playlist.getTracks();
    if (!tracks.isEmpty() && !config.isStreamsEnabled()) {
        tracks = tracks.stream().filter(e -> !e.getInfo().isStream).collect(Collectors.toList());
        if (tracks.isEmpty()) {
            throw new ValidationException("discord.command.audio.queue.limits.streams");
        }
    }

    if (!tracks.isEmpty() && durationLimit != null) {
        tracks = tracks.stream().filter(e -> e.getInfo().isStream || e.getDuration() < (durationLimit * 60000)).collect(Collectors.toList());
        if (tracks.isEmpty()) {
            throw new ValidationException("discord.command.audio.queue.limits.duration.playlist", durationLimit);
        }
    }

    if (instance != null && !tracks.isEmpty() && duplicateLimit != null) {
        List<TrackRequest> queue = instance.getQueue();
        tracks = tracks.stream().filter(e -> queue.stream().filter(e2 -> compareTracks(e2.getTrack(), e)).count() < duplicateLimit).collect(Collectors.toList());
        if (tracks.isEmpty()) {
            throw new ValidationException("discord.command.audio.queue.limits.duplicates.playlist", duplicateLimit);
        }
    }

    if (tracks.isEmpty()) {
        throw new ValidationException("discord.command.audio.queue.limits.playlistEmpty");
    }

    if (instance != null && queueLimit != null) {
        List<TrackRequest> userQueue = instance.getQueue(requestedBy);
        int availableSlots = queueLimit.intValue() - userQueue.size();
        if (availableSlots <= 0) {
            throw new ValidationException("discord.command.audio.queue.limits.items", queueLimit);
        }
        if (tracks.size() > availableSlots) {
            tracks = tracks.subList(0, availableSlots);
        }
    }
    return tracks;
}
 
Example #24
Source File: MusicController.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private void addTrack(final Message message, final String identifier, final boolean now) {
  outputChannel.set((TextChannel) message.getChannel());

  manager.loadItemOrdered(this, identifier, new AudioLoadResultHandler() {
    @Override
    public void trackLoaded(AudioTrack track) {
      connectToFirstVoiceChannel(guild.getAudioManager());

      message.getChannel().sendMessage("Starting now: " + track.getInfo().title + " (length " + track.getDuration() + ")").queue();

      if (now) {
        scheduler.playNow(track, true);
      } else {
        scheduler.addToQueue(track);
      }
    }

    @Override
    public void playlistLoaded(AudioPlaylist playlist) {
      List<AudioTrack> tracks = playlist.getTracks();
      message.getChannel().sendMessage("Loaded playlist: " + playlist.getName() + " (" + tracks.size() + ")").queue();

      connectToFirstVoiceChannel(guild.getAudioManager());

      AudioTrack selected = playlist.getSelectedTrack();

      if (selected != null) {
        message.getChannel().sendMessage("Selected track from playlist: " + selected.getInfo().title).queue();
      } else {
        selected = tracks.get(0);
        message.getChannel().sendMessage("Added first track from playlist: " + selected.getInfo().title).queue();
      }

      if (now) {
        scheduler.playNow(selected, true);
      } else {
        scheduler.addToQueue(selected);
      }

      for (int i = 0; i < Math.min(10, playlist.getTracks().size()); i++) {
        if (tracks.get(i) != selected) {
          scheduler.addToQueue(tracks.get(i));
        }
      }
    }

    @Override
    public void noMatches() {
      message.getChannel().sendMessage("Nothing found for " + identifier).queue();
    }

    @Override
    public void loadFailed(FriendlyException throwable) {
      message.getChannel().sendMessage("Failed with message: " + throwable.getMessage() + " (" + throwable.getClass().getSimpleName() + ")").queue();
    }
  });
}
 
Example #25
Source File: YoutubeMixLoader.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
AudioPlaylist load(
    HttpInterface httpInterface,
    String mixId,
    String selectedVideoId,
    Function<AudioTrackInfo, AudioTrack> trackFactory
);
 
Example #26
Source File: DefaultYoutubePlaylistLoader.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private AudioPlaylist buildPlaylist(HttpInterface httpInterface, JsonBrowser json, String selectedVideoId,
                                    Function<AudioTrackInfo, AudioTrack> trackFactory) throws IOException {

  JsonBrowser jsonResponse = json.index(1).get("response");

  JsonBrowser alerts = jsonResponse.get("alerts");

  if (!alerts.isNull()) {
    throw new FriendlyException(alerts.index(0).get("alertRenderer").get("text").get("simpleText").text(), COMMON, null);
  }

  JsonBrowser info = jsonResponse
      .get("sidebar")
      .get("playlistSidebarRenderer")
      .get("items")
      .index(0)
      .get("playlistSidebarPrimaryInfoRenderer");

  String playlistName = info
      .get("title")
      .get("runs")
      .index(0)
      .get("text")
      .text();

  JsonBrowser playlistVideoList = jsonResponse
      .get("contents")
      .get("twoColumnBrowseResultsRenderer")
      .get("tabs")
      .index(0)
      .get("tabRenderer")
      .get("content")
      .get("sectionListRenderer")
      .get("contents")
      .index(0)
      .get("itemSectionRenderer")
      .get("contents")
      .index(0)
      .get("playlistVideoListRenderer");

  List<AudioTrack> tracks = new ArrayList<>();
  String loadMoreUrl = extractPlaylistTracks(playlistVideoList, tracks, trackFactory);
  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 (!HttpClientTools.isSuccessWithContent(statusCode)) {
        throw new IOException("Invalid status code for playlist response: " + statusCode);
      }

      JsonBrowser continuationJson = JsonBrowser.parse(response.getEntity().getContent());

      JsonBrowser playlistVideoListPage = continuationJson.index(1)
          .get("response")
          .get("continuationContents")
          .get("playlistVideoListContinuation");

      loadMoreUrl = extractPlaylistTracks(playlistVideoListPage, tracks, trackFactory);
    }
  }

  return new BasicAudioPlaylist(playlistName, tracks, findSelectedTrack(tracks, selectedVideoId), false);
}
 
Example #27
Source File: YoutubePlaylistLoader.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId,
Function<AudioTrackInfo, AudioTrack> trackFactory);
 
Example #28
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist playlist) {
  delegate.playlistLoaded(playlist);
}
 
Example #29
Source File: SoundCloudPlaylistLoader.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
AudioPlaylist load(
    String identifier,
    HttpInterfaceManager httpInterfaceManager,
    Function<AudioTrackInfo, AudioTrack> trackFactory
);
 
Example #30
Source File: FunctionalResultHandler.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void playlistLoaded(AudioPlaylist playlist) {
  if (playlistConsumer != null) {
    playlistConsumer.accept(playlist);
  }
}