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

The following examples show how to use com.sedmelluq.discord.lavaplayer.tools.FriendlyException. 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: 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 #2
Source File: SpotifyAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioItem getSpotifyTrack(AudioReference reference) {
    Matcher res = SPOTIFY_TRACK_REGEX.matcher(reference.identifier);
    if (!res.matches()) {
        return null;
    }

    try {
        Future<Track> trackFuture = api.getTrack(res.group(res.groupCount())).build().executeAsync();
        Track track = trackFuture.get();

        /*AudioItem item = youtubeManager.loadItem(null, new AudioReference("ytsearch:" + track.getArtists()[0].getName() + " " + track.getName(), null));
        if (item instanceof AudioPlaylist)
            return ((AudioPlaylist) item).getTracks().get(0);*/
        AudioTrackInfo info = new AudioTrackInfo(track.getName(), track.getArtists()[0].getName(), track.getDurationMs(),
                "ytsearch:" + track.getArtists()[0].getName() + " " + track.getName(), false, null);

        return new SpotifyAudioTrack(info, youtubeManager);
    } catch (Exception e) {
        logger.error("oops!", e);
        throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
    }
}
 
Example #3
Source File: YoutubeAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private static YoutubeAudioSourceManager.UrlInfo getUrlInfo(String url, boolean retryValidPart) {
    try {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "https://" + url;
        }

        URIBuilder builder = new URIBuilder(url);
        return new YoutubeAudioSourceManager.UrlInfo(builder.getPath(), builder.getQueryParams().stream()
                .filter(it -> it.getValue() != null)
                .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue)));
    } catch (URISyntaxException e) {
        if (retryValidPart) {
            return getUrlInfo(url.substring(0, e.getIndex() - 1), false);
        } else {
            throw new FriendlyException("Not a valid URL: " + url, COMMON, e);
        }
    }
}
 
Example #4
Source File: DefaultSoundCloudPlaylistLoader.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
protected AudioPlaylist loadFromSet(
    HttpInterfaceManager httpInterfaceManager,
    String playlistWebUrl,
    Function<AudioTrackInfo, AudioTrack> trackFactory
) {
  try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) {
    JsonBrowser rootData = htmlDataLoader.load(httpInterface, playlistWebUrl);
    JsonBrowser playlistData = dataReader.findPlaylistData(rootData);

    return new BasicAudioPlaylist(
        dataReader.readPlaylistName(playlistData),
        loadPlaylistTracks(httpInterface, playlistData, trackFactory),
        null,
        false
    );
  } catch (IOException e) {
    throw new FriendlyException("Loading playlist from SoundCloud failed.", SUSPICIOUS, e);
  }
}
 
Example #5
Source File: YoutubeAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private JsonBrowser loadTrackBaseInfoFromEmbedPage(HttpInterface httpInterface, String videoId) throws IOException {
    try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.youtube.com/embed/" + videoId))) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new IOException("Invalid status code for embed video page response: " + statusCode);
        }

        String html = IOUtils.toString(response.getEntity().getContent(), Charset.forName(CHARSET));
        String configJson = DataFormatTools.extractBetween(html, "'PLAYER_CONFIG': ", "});writeEmbed();");

        if (configJson != null) {
            return JsonBrowser.parse(configJson);
        }
    }

    throw new FriendlyException("Track information is unavailable.", SUSPICIOUS,
            new IllegalStateException("Expected player config is not present in embed page."));
}
 
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: 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 #8
Source File: NicoAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioTrack loadTrack(String videoId) {
    checkLoggedIn();

    try (HttpInterface httpInterface = getHttpInterface()) {
        try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.nicovideo.jp/watch/" + videoId))) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("Unexpected response code from video info: " + statusCode);
            }

            Document document = Jsoup.parse(response.getEntity().getContent(), StandardCharsets.UTF_8.name(), "", Parser.htmlParser());
            return extractTrackFromHtml(videoId, document);
        }
    } catch (IOException e) {
        throw new FriendlyException("Error occurred when extracting video info.", SUSPICIOUS, e);
    }
}
 
Example #9
Source File: DefaultSoundCloudHtmlDataLoader.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public JsonBrowser load(HttpInterface httpInterface, String url) throws IOException {
  try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(url))) {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
      return JsonBrowser.NULL_BROWSER;
    }

    HttpClientTools.assertSuccessWithContent(response, "video page response");

    String html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
    String rootData = extractJsonFromHtml(html);

    if (rootData == null) {
      throw new FriendlyException("This url does not appear to be a playable track.", SUSPICIOUS, null);
    }

    return JsonBrowser.parse(rootData);
  }
}
 
Example #10
Source File: SafeHttpAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private MediaContainerDetectionResult detectContainerWithClient(HttpInterface httpInterface, AudioReference reference) throws IOException {
    try (PersistentHttpStream inputStream = new PersistentHttpStream(httpInterface, new URI(reference.identifier), Long.MAX_VALUE)) {
        if (!trustedDomains.contains(new URI(reference.identifier).getHost().toLowerCase())) return null;

        int statusCode = inputStream.checkStatusCode();
        String redirectUrl = HttpClientTools.getRedirectLocation(reference.identifier, inputStream.getCurrentResponse());

        if (redirectUrl != null) {
            return refer(null, new AudioReference(redirectUrl, null));
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        } else if (!HttpClientTools.isSuccessWithContent(statusCode)) {
            throw new FriendlyException("That URL is not playable.", COMMON, new IllegalStateException("Status code " + statusCode));
        }

        MediaContainerHints hints = MediaContainerHints.from(getHeaderValue(inputStream.getCurrentResponse(), "Content-Type"), null);
        return new MediaContainerDetection(registry, reference, inputStream, hints).detectContainer();
    } catch (URISyntaxException e) {
        throw new FriendlyException("Not a valid URL.", COMMON, e);
    }
}
 
Example #11
Source File: MpegAudioTrack.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public void process(LocalAudioTrackExecutor localExecutor) {
  MpegFileLoader file = new MpegFileLoader(inputStream);
  file.parseHeaders();

  MpegTrackConsumer trackConsumer = loadAudioTrack(file, localExecutor.getProcessingContext());

  try {
    MpegFileTrackProvider fileReader = file.loadReader(trackConsumer);
    if (fileReader == null) {
      throw new FriendlyException("Unknown MP4 format.", SUSPICIOUS, null);
    }

    accurateDuration.set(fileReader.getDuration());

    localExecutor.executeProcessingLoop(fileReader::provideFrames, fileReader::seekToTimecode);
  } finally {
    trackConsumer.close();
  }
}
 
Example #12
Source File: YoutubeMpegStreamAudioTrack.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private void processSegmentStream(SeekableInputStream stream, AudioProcessingContext context, TrackState state) throws InterruptedException {
  MpegFileLoader file = new MpegFileLoader(stream);
  file.parseHeaders();

  state.absoluteSequence = extractAbsoluteSequenceFromEvent(file.getLastEventMessage());

  if (state.trackConsumer == null) {
    state.trackConsumer = loadAudioTrack(file, context);
  }

  MpegFileTrackProvider fileReader = file.loadReader(state.trackConsumer);
  if (fileReader == null) {
    throw new FriendlyException("Unknown MP4 format.", SUSPICIOUS, null);
  }

  fileReader.provideFrames();
}
 
Example #13
Source File: EventEmitter.java    From Lavalink with MIT License 6 votes vote down vote up
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
    JSONObject out = new JSONObject();
    out.put("op", "event");
    out.put("type", "TrackExceptionEvent");
    out.put("guildId", linkPlayer.getGuildId());
    try {
        out.put("track", Util.toMessage(audioPlayerManager, track));
    } catch (IOException e) {
        out.put("track", JSONObject.NULL);
    }

    out.put("error", exception.getMessage());

    linkPlayer.getSocket().send(out);
}
 
Example #14
Source File: NicoAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private AudioTrack loadTrack(String videoId) {
  checkLoggedIn();

  try (HttpInterface httpInterface = getHttpInterface()) {
    try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("http://ext.nicovideo.jp/api/getthumbinfo/" + videoId))) {
      int statusCode = response.getStatusLine().getStatusCode();
      if (!HttpClientTools.isSuccessWithContent(statusCode)) {
        throw new IOException("Unexpected response code from video info: " + statusCode);
      }

      Document document = Jsoup.parse(response.getEntity().getContent(), StandardCharsets.UTF_8.name(), "", Parser.xmlParser());
      return extractTrackFromXml(videoId, document);
    }
  } catch (IOException e) {
    throw new FriendlyException("Error occurred when extracting video info.", SUSPICIOUS, e);
  }
}
 
Example #15
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 #16
Source File: PlayerListenerAdapter.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onEvent(PlayerEvent event) {
    IPlayer player = event.getPlayer();
    PlaybackInstance instance = instancesByPlayer.get(player);

    if (event instanceof lavalink.client.player.event.TrackStartEvent) {
        if (instance != null) {
            onTrackStart(instance);
        }
    } else if (event instanceof lavalink.client.player.event.TrackEndEvent) {
        if (instance != null) {
            onTrackEnd(instance, ((lavalink.client.player.event.TrackEndEvent) event).getReason());
        }
    } else if (event instanceof lavalink.client.player.event.TrackExceptionEvent) {
        Exception e = ((lavalink.client.player.event.TrackExceptionEvent) event).getException();
        FriendlyException fe = e instanceof FriendlyException
                ? (FriendlyException) e
                : new FriendlyException("Unexpected exception", FriendlyException.Severity.SUSPICIOUS, e);
        onTrackException(instance, fe);
    } else if (event instanceof lavalink.client.player.event.TrackStuckEvent) {
        onTrackStuck(instance);
    }
}
 
Example #17
Source File: LocalAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private boolean handlePlaybackInterrupt(InterruptedException interruption, SeekExecutor seekExecutor) {
  Thread.interrupted();

  if (checkStopped()) {
    markerTracker.trigger(STOPPED);
    return false;
  }

  SeekResult seekResult = checkPendingSeek(seekExecutor);

  if (seekResult != SeekResult.NO_SEEK) {
    // Double-check, might have received a stop request while seeking
    if (checkStopped()) {
      markerTracker.trigger(STOPPED);
      return false;
    } else {
      return seekResult == SeekResult.INTERNAL_SEEK;
    }
  } else if (interruption != null) {
    Thread.currentThread().interrupt();
    throw new FriendlyException("The track was unexpectedly terminated.", SUSPICIOUS, interruption);
  } else {
    return true;
  }
}
 
Example #18
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onTrackException(PlaybackInstance instance, FriendlyException exception) {
    log.warn("Track error", exception);
    Long textChannel = null;
    if (instance.getCurrent() != null) {
        textChannel = instance.getCurrent().getChannelId();
    }
    if (textChannel == null && CollectionUtils.isNotEmpty(instance.getPlaylist())) {
        textChannel = instance.getPlaylist().get(0).getChannelId();
    }
    if (textChannel != null) {
        final long channelId = textChannel;
        contextService.withContext(instance.getGuildId(), () -> messageManager.onQueueError(channelId,
                "discord.command.audio.remote.error", exception.getMessage()));
    }
}
 
Example #19
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 #20
Source File: VimeoAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private AudioTrack loadTrackFromPageContent(String trackUrl, String content) throws IOException {
  JsonBrowser config = loadConfigJsonFromPageContent(content);

  if (config == null) {
    throw new FriendlyException("Track information not found on the page.", SUSPICIOUS, null);
  }

  return new VimeoAudioTrack(new AudioTrackInfo(
      config.get("clip").get("title").text(),
      config.get("owner").get("display_name").text(),
      (long) (config.get("clip").get("duration").get("raw").as(Double.class) * 1000.0),
      trackUrl,
      false,
      trackUrl
  ), this);
}
 
Example #21
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 #22
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean reject(CharArrayBuffer line, int count) {
  if (line.length() > 4 && "ICY ".equals(line.substring(0, 4))) {
    throw new FriendlyException("ICY protocol is not supported.", COMMON, null);
  } else if (count > 10) {
    throw new FriendlyException("The server is giving us garbage.", SUSPICIOUS, null);
  }

  return false;
}
 
Example #23
Source File: DefaultAudioPlayerManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private Future<Void> handleLoadRejected(String identifier, AudioLoadResultHandler resultHandler, RejectedExecutionException e) {
  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 #24
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 #25
Source File: FunctionalResultHandler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Refer to {@link AudioLoadResultHandler} methods for details on when each method is called.
 *
 * @param trackConsumer Consumer for single track result
 * @param playlistConsumer Consumer for playlist result
 * @param emptyResultHandler Empty result handler
 * @param exceptionConsumer Consumer for an exception when loading the item fails
 */
public FunctionalResultHandler(Consumer<AudioTrack> trackConsumer, Consumer<AudioPlaylist> playlistConsumer,
                               Runnable emptyResultHandler, Consumer<FriendlyException> exceptionConsumer) {

  this.trackConsumer = trackConsumer;
  this.playlistConsumer = playlistConsumer;
  this.emptyResultHandler = emptyResultHandler;
  this.exceptionConsumer = exceptionConsumer;
}
 
Example #26
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 #27
Source File: LocalAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private MediaContainerDetectionResult detectContainerForFile(AudioReference reference, File file) {
  try (LocalSeekableInputStream inputStream = new LocalSeekableInputStream(file)) {
    int lastDotIndex = file.getName().lastIndexOf('.');
    String fileExtension = lastDotIndex >= 0 ? file.getName().substring(lastDotIndex + 1) : null;

    return new MediaContainerDetection(containerRegistry, reference, inputStream,
        MediaContainerHints.from(null, fileExtension)).detectContainer();
  } catch (IOException e) {
    throw new FriendlyException("Failed to open file for reading.", SUSPICIOUS, e);
  }
}
 
Example #28
Source File: ProbingAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
protected AudioItem handleLoadResult(MediaContainerDetectionResult result) {
  if (result != null) {
    if (result.isReference()) {
      return result.getReference();
    } else if (!result.isContainerDetected()) {
      throw new FriendlyException("Unknown file format.", COMMON, null);
    } else if (!result.isSupportedFile()) {
      throw new FriendlyException(result.getUnsupportedReason(), COMMON, null);
    } else {
      return createTrack(result.getTrackInfo(), result.getContainerDescriptor());
    }
  }

  return null;
}
 
Example #29
Source File: TwitchStreamAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private JsonBrowser fetchStreamChannelInfo(String name) {
  try (HttpInterface httpInterface = getHttpInterface()) {
    // helix/streams?user_login=name
    HttpUriRequest request = createGetRequest("https://api.twitch.tv/kraken/streams/" + name + "?stream_type=all");

    return HttpClientTools.fetchResponseAsJson(httpInterface, request);
  } catch (IOException e) {
    throw new FriendlyException("Loading Twitch channel information failed.", SUSPICIOUS, e);
  }
}
 
Example #30
Source File: BeamAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private JsonBrowser fetchStreamChannelInfo(String name) {
  try (HttpInterface httpInterface = getHttpInterface()) {
    return HttpClientTools.fetchResponseAsJson(httpInterface,
        new HttpGet("https://mixer.com/api/v1/channels/" + name + "?noCount=1"));
  } catch (IOException e) {
    throw new FriendlyException("Loading Beam channel information failed.", SUSPICIOUS, e);
  }
}