Java Code Examples for com.sedmelluq.discord.lavaplayer.tools.JsonBrowser#isNull()

The following examples show how to use com.sedmelluq.discord.lavaplayer.tools.JsonBrowser#isNull() . 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: 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 2
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 3
Source File: YoutubeSearchProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioTrack extractPolymerData(JsonBrowser json, Function<AudioTrackInfo, AudioTrack> trackFactory) {
  json = json.get("videoRenderer");
  if (json.isNull()) return null; // Ignore everything which is not a track

  String title = json.get("title").get("runs").index(0).get("text").text();
  String author = json.get("ownerText").get("runs").index(0).get("text").text();
  long duration = DataFormatTools.durationTextToMillis(json.get("lengthText").get("simpleText").text());
  String videoId = json.get("videoId").text();

  AudioTrackInfo info = new AudioTrackInfo(title, author, duration, videoId, false,
      WATCH_URL_PREFIX + videoId);

  return trackFactory.apply(info);
}
 
Example 4
Source File: DefaultYoutubeTrackDetailsLoader.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
protected InfoStatus checkStatusBlock(JsonBrowser statusBlock) {
  if (statusBlock.isNull()) {
    throw new RuntimeException("No playability status block.");
  }

  String status = statusBlock.get("status").text();

  if (status == null) {
    throw new RuntimeException("No playability status field.");
  } else if ("OK".equals(status)) {
    return InfoStatus.INFO_PRESENT;
  } else if ("ERROR".equals(status)) {
    String reason = statusBlock.get("reason").text();

    if ("Video unavailable".equals(reason)) {
      return InfoStatus.DOES_NOT_EXIST;
    } else {
      throw new FriendlyException(reason, COMMON, null);
    }
  } else if ("UNPLAYABLE".equals(status)) {
    String unplayableReason = getUnplayableReason(statusBlock);
    throw new FriendlyException(unplayableReason, COMMON, null);
  } else if ("LOGIN_REQUIRED".equals(status)) {
    String errorReason = statusBlock.get("errorScreen")
            .get("playerErrorMessageRenderer")
            .get("reason")
            .get("simpleText")
            .text();

    if ("Private video".equals(errorReason)) {
      throw new FriendlyException("This is a private video.", COMMON, null);
    }

    return InfoStatus.REQUIRES_LOGIN;
  } else {
    throw new FriendlyException("This video cannot be viewed anonymously.", COMMON, null);
  }
}
 
Example 5
Source File: DefaultYoutubePlaylistLoader.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private String extractPlaylistTracks(JsonBrowser playlistVideoList, List<AudioTrack> tracks,
                                     Function<AudioTrackInfo, AudioTrack> trackFactory) {

  JsonBrowser trackArray = playlistVideoList.get("contents");

  if (trackArray.isNull()) return null;

  for (JsonBrowser track : trackArray.values()) {
    JsonBrowser item = track.get("playlistVideoRenderer");

    JsonBrowser shortBylineText = item.get("shortBylineText");

    // If the isPlayable property does not exist, it means the video is removed or private
    // If the shortBylineText property does not exist, it means the Track is Region blocked
    if (!item.get("isPlayable").isNull() && !shortBylineText.isNull()) {
      String videoId = item.get("videoId").text();
      String title = item.get("title").get("simpleText").text();
      String author = shortBylineText.get("runs").index(0).get("text").text();
      JsonBrowser lengthSeconds = item.get("lengthSeconds");
      long duration = Units.secondsToMillis(lengthSeconds.asLong(Units.DURATION_SEC_UNKNOWN));

      AudioTrackInfo info = new AudioTrackInfo(title, author, duration, videoId, false,
          "https://www.youtube.com/watch?v=" + videoId);

      tracks.add(trackFactory.apply(info));
    }
  }

  JsonBrowser continuations = playlistVideoList.get("continuations");

  if (!continuations.isNull()) {
    String continuationsToken = continuations.index(0).get("nextContinuationData").get("continuation").text();
    return "/browse_ajax?continuation=" + continuationsToken + "&ctoken=" + continuationsToken + "&hl=en";
  }

  return null;
}
 
Example 6
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 7
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 8
Source File: DefaultYoutubeTrackDetails.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private List<YoutubeTrackFormat> loadTrackFormats(
    HttpInterface httpInterface,
    YoutubeSignatureResolver signatureResolver
) throws Exception {
  JsonBrowser args = info.get("args");

  String adaptiveFormats = args.get("adaptive_fmts").text();
  if (adaptiveFormats != null) {
    return loadTrackFormatsFromAdaptive(adaptiveFormats);
  }

  String playerResponse = args.get("player_response").text();

  if (playerResponse != null) {
    JsonBrowser playerData = JsonBrowser.parse(playerResponse);
    JsonBrowser streamingData = playerData.get("streamingData");
    boolean isLive = playerData.get("videoDetails").get("isLive").asBoolean(false);

    if (!streamingData.isNull()) {
      List<YoutubeTrackFormat> formats = loadTrackFormatsFromStreamingData(streamingData.get("formats"), isLive);
      formats.addAll(loadTrackFormatsFromStreamingData(streamingData.get("adaptiveFormats"), isLive));

      if (!formats.isEmpty()) {
        return formats;
      }
    }
  }

  String dashUrl = args.get("dashmpd").text();
  if (dashUrl != null) {
    return loadTrackFormatsFromDash(dashUrl, httpInterface, signatureResolver);
  }

  String formatStreamMap = args.get("url_encoded_fmt_stream_map").text();
  if (formatStreamMap != null) {
    return loadTrackFormatsFromFormatStreamMap(formatStreamMap);
  }

  log.warn("Video {} with no detected format field, arguments are: {}", videoId, args.format());

  throw new FriendlyException("Unable to play this YouTube track.", SUSPICIOUS,
      new IllegalStateException("No adaptive formats, no dash, no stream map."));
}
 
Example 9
Source File: DefaultYoutubeTrackDetails.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private List<YoutubeTrackFormat> loadTrackFormatsFromStreamingData(JsonBrowser formats, boolean isLive) {
  List<YoutubeTrackFormat> tracks = new ArrayList<>();
  boolean anyFailures = false;

  if (!formats.isNull() && formats.isList()) {
    for (JsonBrowser formatJson : formats.values()) {
      String cipher = formatJson.get("cipher").text();

      if (cipher == null) {
        cipher = formatJson.get("signatureCipher").text();
      }

      Map<String, String> cipherInfo = cipher != null
          ? decodeUrlEncodedItems(cipher, true)
          : Collections.emptyMap();

      try {
        long contentLength = formatJson.get("contentLength").asLong(CONTENT_LENGTH_UNKNOWN);

        if (contentLength == CONTENT_LENGTH_UNKNOWN && !isLive) {
          log.debug("Track not a live stream, but no contentLength in format {}, skipping", formatJson.format());
          continue;
        }

        tracks.add(new YoutubeTrackFormat(
            ContentType.parse(formatJson.get("mimeType").text()),
            formatJson.get("bitrate").asLong(Units.BITRATE_UNKNOWN),
            contentLength,
            cipherInfo.getOrDefault("url", formatJson.get("url").text()),
            cipherInfo.get("s"),
            cipherInfo.getOrDefault("sp", DEFAULT_SIGNATURE_KEY)
        ));
      } catch (RuntimeException e) {
        anyFailures = true;
        log.debug("Failed to parse format {}, skipping", formatJson, e);
      }
    }
  }

  if (tracks.isEmpty() && anyFailures) {
    log.warn("In streamingData adaptive formats {}, all formats either failed to load or were skipped due to missing " +
        "fields", formats.format());
  }

  return tracks;
}