com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler Java Examples

The following examples show how to use com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler. 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: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private Callable<Void> createItemLoader(final String identifier, final AudioLoadResultHandler resultHandler, boolean isPatron) {
    return () -> {
        final boolean[] reported = new boolean[1];

        try {
            if (!checkSourcesForItem(new AudioReference(identifier, null), resultHandler, reported, isPatron)) {
                log.debug("No matches for track with identifier {}.", identifier);
                resultHandler.noMatches();
            }
        } catch (Throwable throwable) {
            if (reported[0]) {
                log.warn("Load result handler for {} threw an exception", identifier, throwable);
            } else {
                dispatchItemLoadFailure(identifier, resultHandler, throwable);
            }

            ExceptionTools.rethrowErrors(throwable);
        }

        return null;
    };
}
 
Example #2
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private boolean loadFromStream(String identifier, AudioLoadResultHandler resultHandler) {
  try {
    StreamInstance stream;

    synchronized (streams) {
      String finalIdentifier = defaultOnNull(resolutionCache.get(identifier), identifier);
      stream = streams.get(finalIdentifier);
    }

    if (stream != null) {
      AudioTrack track = stream.getTrack().makeClone();
      log.debug("Track {} (originally {}) loaded using existing stream.", track.getIdentifier(), identifier);

      resultHandler.trackLoaded(track);
      return true;
    }
  } catch (Exception e) {
    log.error("Error when checking streams for identifier {}.", identifier);
  }

  return false;
}
 
Example #3
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 #4
Source File: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public Future<Void> loadItemOrdered(final Object orderingKey, final String identifier,
                                    final AudioLoadResultHandler resultHandler, final boolean isPatron) {

    try {
        return orderedInfoExecutor.get().submit(orderingKey, createItemLoader(identifier, resultHandler, isPatron));
    } catch (RejectedExecutionException e) {
        return handleLoadRejected(identifier, resultHandler, e);
    }
}
 
Example #5
Source File: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private Future<Void> handleLoadRejected(String identifier, AudioLoadResultHandler resultHandler, RejectedExecutionException e) {
    final FriendlyException exception = new FriendlyException("Cannot queue loading a track, queue is full.", SUSPICIOUS, e);
    ExceptionTools.log(log, exception, "queueing item " + identifier);

    resultHandler.loadFailed(exception);

    return ExecutorTools.COMPLETED_VOID;
}
 
Example #6
Source File: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void dispatchItemLoadFailure(String identifier, AudioLoadResultHandler resultHandler, Throwable throwable) {
    final FriendlyException exception = ExceptionTools.wrapUnfriendlyExceptions("Something went wrong when looking up the track", FAULT, throwable);

    if (!(throwable instanceof LimitReachedException)) {
        ExceptionTools.log(log, exception, "loading item " + identifier);
    }

    resultHandler.loadFailed(exception);
}
 
Example #7
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 #8
Source File: PlaylistAudioSourceManager.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    try {
        sourceMethod = DefaultAudioPlayerManager.class.getDeclaredMethod("checkSourcesForItem",
                AudioReference.class, AudioLoadResultHandler.class, boolean[].class);
        sourceMethod.setAccessible(true);
    } catch (NoSuchMethodException e) {
        log.warn("Could not get LavaPlayer init method");
    }
}
 
Example #9
Source File: PlaylistAudioSourceManager.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private boolean checkSourcesForItem(DefaultAudioPlayerManager manager, AudioReference reference, AudioLoadResultHandler resultHandler) {
    if (sourceMethod == null) {
        return false;
    }
    try {
        Object result = sourceMethod.invoke(manager, reference, resultHandler, new boolean[1]);
        return Boolean.TRUE.equals(result);
    } catch (IllegalAccessException | InvocationTargetException e) {
        log.warn("Could not invoke checkSourcesForItem of LavaPlayer");
        return false;
    }
}
 
Example #10
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> loadItem(String identifier, AudioLoadResultHandler resultHandler) {
  if (loadFromStream(identifier, resultHandler)) {
    return ExecutorTools.COMPLETED_VOID;
  }

  return super.loadItem(identifier, new SpyingHandler(resultHandler, identifier));
}
 
Example #11
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> loadItemOrdered(Object orderingKey, String identifier, AudioLoadResultHandler resultHandler) {
  if (loadFromStream(identifier, resultHandler)) {
    // This bypasses the ordering but oh well.
    return ExecutorTools.COMPLETED_VOID;
  }

  return super.loadItemOrdered(orderingKey, identifier, resultHandler);
}
 
Example #12
Source File: LavalinkTrackLoader.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void load(AudioPlayerManager manager, Lavalink<?> lavalink, String query,
                        AudioLoadResultHandler handler) {
    Iterator<LavalinkSocket> sockets = lavalink.getNodes().iterator();
    if (!sockets.hasNext()) {
        manager.loadItem(query, handler);
        return;
    }

    CompletionStage<Runnable> last = tryLoad(manager, sockets.next().getRemoteUri(), query, handler);
    while (sockets.hasNext()) {
        URI uri = sockets.next().getRemoteUri();
        //TODO: java 12 replace this with the line commented below
        var cf = new CompletableFuture<Runnable>();
        last.thenApply(CompletableFuture::completedStage)
                .exceptionally(e -> tryLoad(manager, uri, query, handler))
                .thenCompose(Function.identity())
                .thenAccept(cf::complete)
                .exceptionally(e -> {
                    cf.completeExceptionally(e);
                    return null;
                });
        last = cf;
        //last = last.exceptionallyCompose(e -> tryLoad(manager, uri, query, handler));
    }
    last.whenComplete((ok, oof) -> {
        if (oof != null) {
            handler.loadFailed(new FriendlyException("Failed to load", FriendlyException.Severity.SUSPICIOUS, oof));
        } else {
            ok.run();
        }
    });
}
 
Example #13
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 #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: 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 #16
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 #17
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private SpyingHandler(AudioLoadResultHandler delegate, String identifier) {
  this.delegate = delegate;
  this.identifier = identifier;
}
 
Example #18
Source File: MusicManager.java    From Shadbot with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Schedules loading a track or playlist with the specified identifier. Items loaded with the same
 * guild ID are handled sequentially in the order of calls to this method.
 *
 * @return A future for this operation.
 */
protected Future<Void> loadItemOrdered(long guildId, String identifier, AudioLoadResultHandler listener) {
    return this.audioPlayerManager.loadItemOrdered(guildId, identifier, listener);
}