com.sedmelluq.discord.lavaplayer.tools.ExceptionTools Java Examples

The following examples show how to use com.sedmelluq.discord.lavaplayer.tools.ExceptionTools. 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: MatroskaAudioTrack.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private MatroskaTrackConsumer loadAudioTrack(MatroskaStreamingFile file, AudioProcessingContext context) {
  MatroskaTrackConsumer trackConsumer = null;
  boolean success = false;

  try {
    trackConsumer = selectAudioTrack(file.getTrackList(), context);

    if (trackConsumer == null) {
      throw new IllegalStateException("No supported audio tracks in the file.");
    } else {
      log.debug("Starting to play track with codec {}", trackConsumer.getTrack().codecId);
    }

    trackConsumer.initialise();
    success = true;
  } finally {
    if (!success && trackConsumer != null) {
      ExceptionTools.closeWithWarnings(trackConsumer);
    }
  }

  return trackConsumer;
}
 
Example #2
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a single track from video ID.
 *
 * @param videoId ID of the YouTube video.
 * @param mustExist True if it should throw an exception on missing track, otherwise returns AudioReference.NO_TRACK.
 * @return Loaded YouTube track.
 */
public AudioItem loadTrackWithVideoId(String videoId, boolean mustExist) {
  try (HttpInterface httpInterface = getHttpInterface()) {
    YoutubeTrackDetails details = trackDetailsLoader.loadDetails(httpInterface, videoId);

    if (details == null) {
      if (mustExist) {
        throw new FriendlyException("Video unavailable", COMMON, null);
      } else {
        return AudioReference.NO_TRACK;
      }
    }

    return new YoutubeAudioTrack(details.getTrackInfo(), this);
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions("Loading information for a YouTube track failed.", FAULT, e);
  }
}
 
Example #3
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public AudioItem anonymous(String videoIds) {
  try (HttpInterface httpInterface = getHttpInterface()) {
    try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com/watch_videos?video_ids=" + videoIds))) {
      int statusCode = response.getStatusLine().getStatusCode();
      HttpClientContext context = httpInterface.getContext();
      if (!HttpClientTools.isSuccessWithContent(statusCode)) {
        throw new IOException("Invalid status code for playlist response: " + statusCode);
      }
      // youtube currently transforms watch_video links into a link with a video id and a list id.
      // because thats what happens, we can simply re-process with the redirected link
      List<URI> redirects = context.getRedirectLocations();
      if (redirects != null && !redirects.isEmpty()) {
        return new AudioReference(redirects.get(0).toString(), null);
      } else {
        throw new FriendlyException("Unable to process youtube watch_videos link", SUSPICIOUS,
            new IllegalStateException("Expected youtube to redirect watch_videos link to a watch?v={id}&list={list_id} link, but it did not redirect at all"));
      }
    }
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions(e);
  }
}
 
Example #4
Source File: YoutubeSearchProvider.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
/**
 * @param query Search query.
 * @return Playlist of the first page of results.
 */
@Override
public AudioItem loadSearchResult(String query, Function<AudioTrackInfo, AudioTrack> trackFactory) {
  log.debug("Performing a search with query {}", query);

  try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) {
    URI url = new URIBuilder("https://www.youtube.com/results").addParameter("search_query", query).build();

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

      Document document = Jsoup.parse(response.getEntity().getContent(), StandardCharsets.UTF_8.name(), "");
      return extractSearchResults(document, query, trackFactory);
    }
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions(e);
  }
}
 
Example #5
Source File: HttpStreamTools.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
public static InputStream streamContent(HttpInterface httpInterface, HttpUriRequest request) {
  CloseableHttpResponse response = null;
  boolean success = false;

  try {
    response = httpInterface.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();

    if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code from " + request.getURI() + " URL: " + statusCode);
    }

    success = true;
    return response.getEntity().getContent();
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (response != null && !success) {
      ExceptionTools.closeWithWarnings(response);
    }
  }
}
 
Example #6
Source File: TrustManagerBuilder.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private void addFromResourceList(String basePath, String listPath) throws Exception {
  InputStream listFileStream = TrustManagerBuilder.class.getResourceAsStream(listPath);

  if (listFileStream == null) {
    log.debug("Certificate list {} not present in classpath.", listPath);
    return;
  }

  try {
    for (String line : IOUtils.readLines(listFileStream, StandardCharsets.UTF_8)) {
      String fileName = line.trim();

      if (!fileName.isEmpty()) {
        addFromResourceFile(basePath + "/" + fileName);
      }
    }
  } finally {
    ExceptionTools.closeWithWarnings(listFileStream);
  }
}
 
Example #7
Source File: TrustManagerBuilder.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private void addFromResourceFile(String resourcePath) throws Exception {
  InputStream fileStream = TrustManagerBuilder.class.getResourceAsStream(resourcePath);

  if (fileStream == null) {
    log.warn("Certificate {} not present in classpath.", resourcePath);
    return;
  }

  try {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(fileStream, null);
    addFromKeyStore(keyStore);
  } finally {
    ExceptionTools.closeWithWarnings(fileStream);
  }
}
 
Example #8
Source File: MediaContainerDetection.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
/**
 * @return Result of detection.
 */
public MediaContainerDetectionResult detectContainer() {
  MediaContainerDetectionResult result;

  try {
    SavedHeadSeekableInputStream savedHeadInputStream = new SavedHeadSeekableInputStream(inputStream, HEAD_MARK_LIMIT);
    savedHeadInputStream.loadHead();

    result = detectContainer(savedHeadInputStream, true);

    if (result == null) {
      result = detectContainer(savedHeadInputStream, false);
    }
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions("Could not read the file for detecting file type.", SUSPICIOUS, e);
  }

  return result != null ? result : unknownFormat();
}
 
Example #9
Source File: DefaultAudioPlayerManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private Callable<Void> createItemLoader(final String identifier, final AudioLoadResultHandler resultHandler) {
  return () -> {
    boolean[] reported = new boolean[1];

    try {
      if (!checkSourcesForItem(new AudioReference(identifier, null), resultHandler, reported)) {
        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 #10
Source File: MpegAudioTrack.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
protected MpegTrackConsumer loadAudioTrack(MpegFileLoader file, AudioProcessingContext context) {
  MpegTrackConsumer trackConsumer = null;
  boolean success = false;

  try {
    trackConsumer = selectAudioTrack(file.getTrackList(), context);

    if (trackConsumer == null) {
      throw new FriendlyException("The audio codec used in the track is not supported.", SUSPICIOUS, null);
    } else {
      log.debug("Starting to play track with codec {}", trackConsumer.getTrack().codecName);
    }

    trackConsumer.initialise();
    success = true;
    return trackConsumer;
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions("Something went wrong when loading an MP4 format track.", FAULT, e);
  } finally {
    if (!success && trackConsumer != null) {
      trackConsumer.close();
    }
  }
}
 
Example #11
Source File: RemoteNodeManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
/**
 * Shut down, freeing all threads and stopping all tracks executed on remote nodes.
 * @param terminal True if initialise will never be called again.
 */
public void shutdown(boolean terminal) {
  synchronized (lock) {
    if (!enabled.compareAndSet(true, false)) {
      return;
    }

    ExecutorTools.shutdownExecutor(scheduler, "node manager");

    for (RemoteNodeProcessor processor : processors) {
      processor.processHealthCheck(true);
    }

    abandonedTrackManager.shutdown();

    processors.clear();
    activeProcessors = new ArrayList<>(processors);
  }

  if (terminal) {
    ExceptionTools.closeWithWarnings(httpInterfaceManager);
  }
}
 
Example #12
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 #13
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 #14
Source File: Variables.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
public DatabaseAdapter getDatabaseAdapter() {
    try {
        if (this.databaseAdapter == null) {
            this.databaseAdapter = this.useApi() ?
                new WebDatabaseAdapter(this.getApis(), this.getJackson()) :
                (DatabaseAdapter) (Class.forName("ml.duncte123.skybot.adapters.SqliteDatabaseAdapter")
                    .getDeclaredConstructor().newInstance());
        }
    }
    catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
        InstantiationException | InvocationTargetException e) {
        LoggerFactory.getLogger(Variables.class).error("Could not load database class.\n" +
            "Are you a developer?", e);

        throw ExceptionTools.wrapUnfriendlyExceptions(e);
    }

    return this.databaseAdapter;
}
 
Example #15
Source File: YoutubeAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioPlaylist loadPlaylistWithId(String playlistId, String selectedVideoId) {
    log.debug("Starting to load playlist with ID {}", playlistId);

    try (HttpInterface httpInterface = getHttpInterface()) {
        try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com/playlist?list=" + playlistId))) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("Invalid status code for playlist response: " + statusCode);
            }

            Document document = Jsoup.parse(response.getEntity().getContent(), CHARSET, "");
            return buildPlaylist(httpInterface, document, selectedVideoId);
        }
    } catch (Exception e) {
        throw ExceptionTools.wrapUnfriendlyExceptions(e);
    }
}
 
Example #16
Source File: YoutubeAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioItem loadAnonymous(String videoIds) {
    try (HttpInterface httpInterface = getHttpInterface()) {
        try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com/watch_videos?video_ids=" + videoIds))) {
            int statusCode = response.getStatusLine().getStatusCode();
            HttpClientContext context = httpInterface.getContext();
            if (statusCode != 200) {
                throw new IOException("Invalid status code for playlist response: " + statusCode);
            }
            // youtube currently transforms watch_video links into a link with a video id and a list id.
            // because thats what happens, we can simply re-process with the redirected link
            List<URI> redirects = context.getRedirectLocations();
            if (redirects != null && !redirects.isEmpty()) {
                return loadNonSearch(redirects.get(0).toString());
            } else {
                throw new FriendlyException("Unable to process youtube watch_videos link", SUSPICIOUS,
                        new IllegalStateException("Expected youtube to redirect watch_videos link to a watch?v={id}&list={list_id} link, but it did not redirect at all"));
            }
        }
    } catch (Exception e) {
        throw ExceptionTools.wrapUnfriendlyExceptions(e);
    }
}
 
Example #17
Source File: RemoteNodeProcessor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private boolean handleResponseBody(InputStream inputStream, TickBuilder tickBuilder) {
  CountingInputStream countingStream = new CountingInputStream(inputStream);
  DataInputStream input = new DataInputStream(countingStream);
  RemoteMessage message;

  try {
    while ((message = mapper.decode(input)) != null) {
      if (message instanceof TrackStartResponseMessage) {
        handleTrackStartResponse((TrackStartResponseMessage) message);
      } else if (message instanceof TrackFrameDataMessage) {
        handleTrackFrameData((TrackFrameDataMessage) message);
      } else if (message instanceof TrackExceptionMessage) {
        handleTrackException((TrackExceptionMessage) message);
      } else if (message instanceof NodeStatisticsMessage) {
        handleNodeStatistics((NodeStatisticsMessage) message);
      }
    }
  } catch (InterruptedException interruption) {
    log.error("Node {} processing thread was interrupted.", nodeAddress);
    Thread.currentThread().interrupt();
    return false;
  } catch (Throwable e) {
    log.error("Error when processing response from node {}.", nodeAddress, e);
    ExceptionTools.rethrowErrors(e);
  } finally {
    tickBuilder.responseSize = countingStream.getCount();
  }

  return true;
}
 
Example #18
Source File: MatroskaAudioTrack.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void process(LocalAudioTrackExecutor localExecutor) {
  MatroskaStreamingFile file = loadMatroskaFile();
  MatroskaTrackConsumer trackConsumer = loadAudioTrack(file, localExecutor.getProcessingContext());

  try {
    localExecutor.executeProcessingLoop(() -> {
      file.provideFrames(trackConsumer);
    }, position -> {
      file.seekToTimecode(trackConsumer.getTrack().index, position);
    });
  } finally {
    ExceptionTools.closeWithWarnings(trackConsumer);
  }
}
 
Example #19
Source File: HttpInterface.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given query using the client and context stored in this instance.
 *
 * @param request The request to execute.
 * @return Closeable response from the server.
 * @throws IOException On network error.
 */
public CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
  boolean isRepeated = false;

  while (true) {
    filter.onRequest(context, request, isRepeated);

    try {
      CloseableHttpResponse response = client.execute(request, context);
      lastRequest = request;

      if (!filter.onRequestResponse(context, request, response)) {
        return response;
      }
    } catch (Throwable e) {
      if (!filter.onRequestException(context, request, e)) {
        if (e instanceof Error) {
          throw (Error) e;
        } else if (e instanceof RuntimeException) {
          throw (RuntimeException) e;
        } else //noinspection ConstantConditions
          if (e instanceof IOException) {
          throw (IOException) e;
        } else {
          throw new RuntimeException(e);
        }
      } else {
        ExceptionTools.rethrowErrors(e);
      }
    }

    isRepeated = true;
  }
}
 
Example #20
Source File: RemoteAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Send the specified exception as an event to the active state listener.
 * @param exception Exception to send
 */
public void dispatchException(FriendlyException exception) {
  TrackStateListener currentListener = activeListener;

  ExceptionTools.log(log, exception, track.getIdentifier());

  if (currentListener != null) {
    trackException = exception;
    currentListener.onTrackException(track, exception);
  }
}
 
Example #21
Source File: RemoteAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(TrackStateListener listener) {
  try {
    hasStarted = true;
    activeListener = listener;
    remoteNodeManager.startPlaying(this);
  } catch (Throwable throwable) {
    listener.onTrackException(track, ExceptionTools.wrapUnfriendlyExceptions(
        "An error occurred when trying to start track remotely.", FriendlyException.Severity.FAULT, throwable));

    ExceptionTools.rethrowErrors(throwable);
  }
}
 
Example #22
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem mix(String mixId, String selectedVideoId) {
  log.debug("Starting to load mix with ID {} selected track {}", mixId, selectedVideoId);

  try (HttpInterface httpInterface = getHttpInterface()) {
    return mixLoader.load(httpInterface, mixId, selectedVideoId,
        YoutubeAudioSourceManager.this::buildTrackFromInfo);
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions(e);
  }
}
 
Example #23
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem playlist(String playlistId, String selectedVideoId) {
  log.debug("Starting to load playlist with ID {}", playlistId);

  try (HttpInterface httpInterface = getHttpInterface()) {
    return playlistLoader.load(httpInterface, playlistId, selectedVideoId,
        YoutubeAudioSourceManager.this::buildTrackFromInfo);
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions(e);
  }
}
 
Example #24
Source File: BandcampAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem extractFromPage(String url, AudioItemExtractor extractor) {
  try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) {
    return extractFromPageWithInterface(httpInterface, url, extractor);
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions("Loading information for a Bandcamp track failed.", FAULT, e);
  }
}
 
Example #25
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 #26
Source File: M3uStreamSegmentUrlProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the input stream for the next segment in the M3U stream.
 *
 * @param httpInterface HTTP interface to use for any requests required to perform to find the segment URL.
 * @return Input stream of the next segment.
 */
public InputStream getNextSegmentStream(HttpInterface httpInterface) {
  String url = getNextSegmentUrl(httpInterface);
  if (url == null) {
    return null;
  }

  CloseableHttpResponse response = null;
  boolean success = false;

  try {
    response = httpInterface.execute(createSegmentGetRequest(url));
    int statusCode = response.getStatusLine().getStatusCode();

    if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code from segment data URL: " + statusCode);
    }

    success = true;
    return response.getEntity().getContent();
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (response != null && !success) {
      ExceptionTools.closeWithWarnings(response);
    }
  }
}
 
Example #27
Source File: AudioFrameProviderTools.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * @param provider Delegates a call to frame provide without timeout to the timed version of it.
 * @return The audio frame from provide method.
 */
public static AudioFrame delegateToTimedProvide(AudioFrameProvider provider) {
  try {
    return provider.provide(0, TimeUnit.MILLISECONDS);
  } catch (TimeoutException | InterruptedException e) {
    ExceptionTools.keepInterrupted(e);
    throw new RuntimeException(e);
  }
}
 
Example #28
Source File: LocalAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private void performSeek(SeekExecutor seekExecutor, long seekPosition) {
  try {
    seekExecutor.performSeek(seekPosition);
  } catch (Exception e) {
    throw ExceptionTools.wrapUnfriendlyExceptions("Something went wrong when seeking to a position.", FAULT, e);
  }
}
 
Example #29
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 #30
Source File: DefaultAudioPlayer.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean provide(MutableAudioFrame targetFrame) {
  try {
    return provide(targetFrame, 0, TimeUnit.MILLISECONDS);
  } catch (TimeoutException | InterruptedException e) {
    ExceptionTools.keepInterrupted(e);
    throw new RuntimeException(e);
  }
}