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

The following examples show how to use com.sedmelluq.discord.lavaplayer.track.AudioItem. 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: TwitchStreamAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
    String streamName = getChannelIdentifierFromUrl(reference.identifier);
    if (streamName == null) {
        return null;
    }

    JsonBrowser channelInfo = fetchChannelInfo(streamName);

    if (channelInfo == null) {
        return AudioReference.NO_TRACK;
    } else {
        final String displayName = channelInfo.get("display_name").text();
        final String status = channelInfo.get("status").text();

        return new TwitchStreamAudioTrack(new AudioTrackInfo(
                status,
                displayName,
                Long.MAX_VALUE,
                reference.identifier,
                true,
                reference.identifier
        ), this);
    }
}
 
Example #2
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 #3
Source File: RandomExtractor.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void process(String input, Player player, Message message, User user) throws Exception {
    int i = 0;
    for (String s : input.split(",")) {
        try {
            AudioItem probablyATrack = player.resolve(s);
            if (probablyATrack == null)
                continue;
            Track track = new Track((AudioTrack) probablyATrack);
            track.getMeta().put("requester", user.getId());
            track.getMeta().put("guildId", player.getGuildId());
            player.queue(track);
            i++;
        } catch (FriendlyException ignored) {
        }
    }
    MessageUtils.editMessage(null, MessageUtils.getEmbed()
            .setDescription("Added " + i + " random songs to the playlist!"), message);
}
 
Example #4
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 #5
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  AudioItem track = processAsSingleTrack(reference);

  if (track == null) {
    track = playlistLoader.load(reference.identifier, httpInterfaceManager, this::buildTrackFromInfo);
  }

  if (track == null) {
    track = processAsLikedTracks(reference);
  }

  if (track == null && allowSearch) {
    track = processAsSearchQuery(reference);
  }

  return track;
}
 
Example #6
Source File: BandcampAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private AudioItem extractFromPageWithInterface(HttpInterface httpInterface, String url, AudioItemExtractor extractor) throws Exception {
  String responseText;

  try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(url))) {
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_NOT_FOUND) {
      return new AudioReference(null, null);
    } else if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code for track page: " + statusCode);
    }

    responseText = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
  }

  return extractor.extract(httpInterface, responseText);
}
 
Example #7
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 #8
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 #9
Source File: HttpAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  AudioReference httpReference = getAsHttpReference(reference);
  if (httpReference == null) {
    return null;
  }

  if (httpReference.containerDescriptor != null) {
    return createTrack(AudioTrackInfoBuilder.create(reference, null).build(), httpReference.containerDescriptor);
  } else {
    return handleLoadResult(detectContainer(httpReference));
  }
}
 
Example #10
Source File: VimeoAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem loadFromTrackPage(HttpInterface httpInterface, String trackUrl) throws IOException {
  try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(trackUrl))) {
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_NOT_FOUND) {
      return AudioReference.NO_TRACK;
    } else if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new FriendlyException("Server responded with an error.", SUSPICIOUS,
          new IllegalStateException("Response code is " + statusCode));
    }

    return loadTrackFromPageContent(trackUrl, IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
  }
}
 
Example #11
Source File: BeamAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  String streamName = getChannelNameFromUrl(reference.identifier);
  if (streamName == null) {
    return null;
  }

  JsonBrowser channelInfo = fetchStreamChannelInfo(streamName);

  if (channelInfo == null) {
    return AudioReference.NO_TRACK;
  } else {
    String displayName = channelInfo.get("name").text();
    String id = getPlayedStreamId(channelInfo);

    if (displayName == null || id == null) {
      throw new IllegalStateException("Expected id and name fields from Beam channel info.");
    }

    return new BeamAudioTrack(new AudioTrackInfo(
        displayName,
        streamName,
        Units.DURATION_MS_UNKNOWN,
        id + "|" + streamName + "|" + reference.identifier,
        true,
        "https://beam.pro/" + streamName
    ), this);
  }
}
 
Example #12
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem processAsLikedTracks(AudioReference reference) {
  String url = SoundCloudHelper.nonMobileUrl(reference.identifier);

  if (likedUrlPattern.matcher(url).matches()) {
    return loadFromLikedTracks(url);
  } else {
    return null;
  }
}
 
Example #13
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem loadFromLikedTracks(String likedListUrl) {
  try (HttpInterface httpInterface = getHttpInterface()) {
    UserInfo userInfo = findUserIdFromLikedList(httpInterface, likedListUrl);
    if (userInfo == null) {
      return AudioReference.NO_TRACK;
    }

    return extractTracksFromLikedList(loadLikedListForUserId(httpInterface, userInfo), userInfo);
  } catch (IOException e) {
    throw new FriendlyException("Loading liked tracks from SoundCloud failed.", SUSPICIOUS, e);
  }
}
 
Example #14
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem extractTracksFromLikedList(JsonBrowser likedTracks, UserInfo userInfo) {
  List<AudioTrack> tracks = new ArrayList<>();

  for (JsonBrowser item : likedTracks.get("collection").values()) {
    JsonBrowser trackItem = item.get("track");

    if (!trackItem.isNull() && !dataReader.isTrackBlocked(trackItem)) {
      tracks.add(loadFromTrackData(trackItem));
    }
  }

  return new BasicAudioPlaylist("Liked by " + userInfo.name, tracks, null, false);
}
 
Example #15
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem processAsSearchQuery(AudioReference reference) {
  if (reference.identifier.startsWith(SEARCH_PREFIX)) {
    if (reference.identifier.startsWith(SEARCH_PREFIX_DEFAULT)) {
      return loadSearchResult(reference.identifier.substring(SEARCH_PREFIX_DEFAULT.length()).trim(), 0, DEFAULT_SEARCH_RESULTS);
    }

    Matcher searchMatcher = searchPattern.matcher(reference.identifier);

    if (searchMatcher.matches()) {
      return loadSearchResult(searchMatcher.group(3), Integer.parseInt(searchMatcher.group(1)), Integer.parseInt(searchMatcher.group(2)));
    }
  }

  return null;
}
 
Example #16
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem loadSearchResult(String query, int offset, int rawLimit) {
  int limit = Math.min(rawLimit, MAXIMUM_SEARCH_RESULTS);

  try (
      HttpInterface httpInterface = getHttpInterface();
      CloseableHttpResponse response = httpInterface.execute(new HttpGet(buildSearchUri(query, offset, limit)))
  ) {
    return loadSearchResultsFromResponse(response, query);
  } catch (IOException e) {
    throw new FriendlyException("Loading search results from SoundCloud failed.", SUSPICIOUS, e);
  }
}
 
Example #17
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem loadSearchResultsFromResponse(HttpResponse response, String query) throws IOException {
  try {
    JsonBrowser searchResults = JsonBrowser.parse(response.getEntity().getContent());
    return extractTracksFromSearchResults(query, searchResults);
  } finally {
    EntityUtils.consumeQuietly(response.getEntity());
  }
}
 
Example #18
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem extractTracksFromSearchResults(String query, JsonBrowser searchResults) {
  List<AudioTrack> tracks = new ArrayList<>();

  for (JsonBrowser item : searchResults.get("collection").values()) {
    if (!item.isNull()) {
      tracks.add(loadFromTrackData(item));
    }
  }

  return new BasicAudioPlaylist("Search results for: " + query, tracks, null, true);
}
 
Example #19
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  try {
    return loadItemOnce(reference);
  } catch (FriendlyException exception) {
    // In case of a connection reset exception, try once more.
    if (HttpClientTools.isRetriableNetworkException(exception.getCause())) {
      return loadItemOnce(reference);
    } else {
      throw exception;
    }
  }
}
 
Example #20
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 #21
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 #22
Source File: YoutubeAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem search(String query) {
  if (allowSearch) {
    return searchResultLoader.loadSearchResult(
        query,
        YoutubeAudioSourceManager.this::buildTrackFromInfo
    );
  } else {
    return null;
  }
}
 
Example #23
Source File: YoutubeSearchProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem extractSearchResults(Document document, String query,
                                       Function<AudioTrackInfo, AudioTrack> trackFactory) {

  List<AudioTrack> tracks = new ArrayList<>();
  Elements resultsSelection = document.select("#page > #content #results");
  if (!resultsSelection.isEmpty()) {
    for (Element results : resultsSelection) {
      for (Element result : results.select(".yt-lockup-video")) {
        if (!result.hasAttr("data-ad-impressions") && result.select(".standalone-ypc-badge-renderer-label").isEmpty()) {
          extractTrackFromResultEntry(tracks, result, trackFactory);
        }
      }
    }
  } else {
    log.debug("Attempting to parse results page as polymer");
    try {
      tracks = polymerExtractTracks(document, trackFactory);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  if (tracks.isEmpty()) {
    return AudioReference.NO_TRACK;
  } else {
    return new BasicAudioPlaylist("Search results for: " + query, tracks, null, true);
  }
}
 
Example #24
Source File: GetyarnAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  final Matcher m = GETYARN_REGEX.matcher(reference.identifier);

  if (!m.matches()) {
    return null;
  }

  return extractVideoUrlFromPage(reference);
}
 
Example #25
Source File: VimeoAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
  if (!trackUrlPattern.matcher(reference.identifier).matches()) {
    return null;
  }

  try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) {
    return loadFromTrackPage(httpInterface, reference.identifier);
  } catch (IOException e) {
    throw new FriendlyException("Loading Vimeo track information failed.", SUSPICIOUS, e);
  }
}
 
Example #26
Source File: NicoAudioSourceManager.java    From kyoko with MIT License 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
    Matcher trackMatcher = trackUrlPattern.matcher(reference.identifier);

    if (trackMatcher.matches()) {
        return loadTrack(trackMatcher.group(1));
    }

    return null;
}
 
Example #27
Source File: SafeHttpAudioSourceManager.java    From kyoko with MIT License 5 votes vote down vote up
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
    AudioReference httpReference = getAsHttpReference(reference);
    if (httpReference == null) {
        return null;
    }

    if (httpReference.containerDescriptor != null) {
        return createTrack(AudioTrackInfoBuilder.create(reference, null).build(), httpReference.containerDescriptor);
    } else {
        return handleLoadResult(detectContainer(httpReference));
    }
}
 
Example #28
Source File: GeneralUtils.java    From FlareBot with MIT License 5 votes vote down vote up
/**
 * Resolves an {@link AudioItem} from a string.
 * This can be a url or search terms
 *
 * @param player The music player
 * @param input  The string to get the AudioItem from.
 * @return {@link AudioItem} from the string.
 * @throws IllegalArgumentException If the Item couldn't be found due to it not existing on Youtube.
 * @throws IllegalStateException    If the Video is unavailable for Flare, for example if it was published by VEVO.
 */
public static AudioItem resolveItem(Player player, String input) throws IllegalArgumentException, IllegalStateException {
    Optional<AudioItem> item = Optional.empty();
    boolean failed = false;
    int backoff = 2;
    Throwable cause = null;
    for (int i = 0; i <= 2; i++) {
        try {
            item = Optional.ofNullable(player.resolve(input));
            failed = false;
            break;
        } catch (FriendlyException | InterruptedException | ExecutionException e) {
            failed = true;
            cause = e;
            if (e.getMessage().contains("Vevo")) {
                throw new IllegalStateException(Jsoup.clean(cause.getMessage(), Whitelist.none()), cause);
            }
            FlareBot.LOGGER.error(Markers.NO_ANNOUNCE, "Cannot get video '" + input + "'");
            try {
                Thread.sleep(backoff);
            } catch (InterruptedException ignored) {
            }
            backoff ^= 2;
        }
    }
    if (failed) {
        throw new IllegalStateException(Jsoup.clean(cause.getMessage(), Whitelist.none()), cause);
    } else if (!item.isPresent()) {
        throw new IllegalArgumentException();
    }
    return item.get();
}
 
Example #29
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 #30
Source File: YoutubeAudioSourceManagerOverride.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public AudioItem loadTrackWithVideoId(String videoId, boolean mustExist) {
    final CacheResponse cacheResponse = this.cacheClient.get(videoId);

    if (!cacheResponse.failure && cacheResponse.getTrack() != null) {
        final AudioTrack track = cacheResponse.getTrack().toAudioTrack(this);
        return new DoNotCache(track);
    }

    if (mustExist) {
        return getFromYoutubeApi(videoId);
    }

    return super.loadTrackWithVideoId(videoId, mustExist);
}