Java Code Examples for com.sedmelluq.discord.lavaplayer.tools.ExceptionTools#wrapUnfriendlyExceptions()

The following examples show how to use com.sedmelluq.discord.lavaplayer.tools.ExceptionTools#wrapUnfriendlyExceptions() . 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: 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 2
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 3
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 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: 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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Source File: LocalAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(TrackStateListener listener) {
  InterruptedException interrupt = null;

  if (Thread.interrupted()) {
    log.debug("Cleared a stray interrupt.");
  }

  if (playingThread.compareAndSet(null, Thread.currentThread())) {
    log.debug("Starting to play track {} locally with listener {}", audioTrack.getInfo().identifier, listener);

    state.set(AudioTrackState.LOADING);

    try {
      audioTrack.process(this);

      log.debug("Playing track {} finished or was stopped.", audioTrack.getIdentifier());
    } catch (Throwable e) {
      // Temporarily clear the interrupted status so it would not disrupt listener methods.
      interrupt = findInterrupt(e);

      if (interrupt != null && checkStopped()) {
        log.debug("Track {} was interrupted outside of execution loop.", audioTrack.getIdentifier());
      } else {
        frameBuffer.setTerminateOnEmpty();

        FriendlyException exception = ExceptionTools.wrapUnfriendlyExceptions("Something broke when playing the track.", FAULT, e);
        ExceptionTools.log(log, exception, "playback of " + audioTrack.getIdentifier());

        trackException = exception;
        listener.onTrackException(audioTrack, exception);

        ExceptionTools.rethrowErrors(e);
      }
    } finally {
      synchronized (actionSynchronizer) {
        interrupt = interrupt != null ? interrupt : findInterrupt(null);

        playingThread.compareAndSet(Thread.currentThread(), null);

        markerTracker.trigger(ENDED);
        state.set(AudioTrackState.FINISHED);
      }

      if (interrupt != null) {
        Thread.currentThread().interrupt();
      }
    }
  } else {
    log.warn("Tried to start an already playing track {}", audioTrack.getIdentifier());
  }
}
 
Example 16
Source File: LocalAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
/**
 * Execute the read and seek loop for the track.
 * @param readExecutor Callback for reading the track
 * @param seekExecutor Callback for performing a seek on the track, may be null on a non-seekable track
 */
public void executeProcessingLoop(ReadExecutor readExecutor, SeekExecutor seekExecutor, boolean waitOnEnd) {
  boolean proceed = true;

  if (checkPendingSeek(seekExecutor) == SeekResult.EXTERNAL_SEEK) {
    return;
  }

  while (proceed) {
    state.set(AudioTrackState.PLAYING);
    proceed = false;

    try {
      // An interrupt may have been placed while we were handling the previous one.
      if (Thread.interrupted() && !handlePlaybackInterrupt(null, seekExecutor)) {
        break;
      }

      setInterruptibleForSeek(true);
      readExecutor.performRead();
      setInterruptibleForSeek(false);

      if (seekExecutor != null && externalSeekPosition != -1) {
        long nextPosition = externalSeekPosition;
        externalSeekPosition = -1;
        performSeek(seekExecutor, nextPosition);
        proceed = true;
      } else if (waitOnEnd) {
        waitOnEnd();
      }
    } catch (Exception e) {
      setInterruptibleForSeek(false);
      InterruptedException interruption = findInterrupt(e);

      if (interruption != null) {
        proceed = handlePlaybackInterrupt(interruption, seekExecutor);
      } else {
        throw ExceptionTools.wrapUnfriendlyExceptions("Something went wrong when decoding the track.", FAULT, e);
      }
    }
  }
}
 
Example 17
Source File: DefaultAudioPlayerManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private void dispatchItemLoadFailure(String identifier, AudioLoadResultHandler resultHandler, Throwable throwable) {
  FriendlyException exception = ExceptionTools.wrapUnfriendlyExceptions("Something went wrong when looking up the track", FAULT, throwable);
  ExceptionTools.log(log, exception, "loading item " + identifier);

  resultHandler.loadFailed(exception);
}