Search in sources :

Example 1 with UnavailableResourceException

use of net.robinfriedli.aiode.exceptions.UnavailableResourceException in project aiode by robinfriedli.

the class YouTubeService method loadDurationsAsync.

private void loadDurationsAsync(List<HollowYouTubeVideo> videos) {
    // ids have already been loaded in other thread
    List<String> videoIds = Lists.newArrayList();
    for (HollowYouTubeVideo hollowYouTubeVideo : videos) {
        String id;
        try {
            id = hollowYouTubeVideo.getVideoId();
        } catch (UnavailableResourceException e) {
            continue;
        }
        videoIds.add(id);
    }
    if (videoIds.isEmpty()) {
        return;
    }
    EagerFetchQueue.submitFetch(() -> {
        try {
            Map<String, Long> durationMillis = getDurationMillis(videoIds);
            for (HollowYouTubeVideo video : videos) {
                Long duration;
                try {
                    duration = durationMillis.get(video.getVideoId());
                } catch (UnavailableResourceException e) {
                    continue;
                }
                video.setDuration(duration != null ? duration : 0);
            }
        } catch (IOException e) {
            throw new RuntimeException("Exception occurred while loading durations", e);
        }
    });
}
Also used : CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) IOException(java.io.IOException)

Example 2 with UnavailableResourceException

use of net.robinfriedli.aiode.exceptions.UnavailableResourceException in project aiode by robinfriedli.

the class SpotifyRedirectService method redirectTrack.

public void redirectTrack(HollowYouTubeVideo youTubeVideo) throws IOException {
    SpotifyTrack spotifyTrack = youTubeVideo.getRedirectedSpotifyTrack();
    if (spotifyTrack == null) {
        throw new IllegalArgumentException(youTubeVideo.toString() + " is not a placeholder for a redirected Spotify Track");
    }
    // early exit to avoid duplicate loading of Playables that have been loaded prioritised by invoking Playable#fetchNow
    if (youTubeVideo.isDone()) {
        return;
    }
    youTubeVideo.markLoading();
    String spotifyTrackId = spotifyTrack.getId();
    Optional<SpotifyRedirectIndex> persistedSpotifyRedirectIndex;
    if (!Strings.isNullOrEmpty(spotifyTrackId)) {
        persistedSpotifyRedirectIndex = queryExistingIndex(session, spotifyTrackId);
    } else {
        persistedSpotifyRedirectIndex = Optional.empty();
    }
    if (persistedSpotifyRedirectIndex.isPresent()) {
        SpotifyRedirectIndex spotifyRedirectIndex = persistedSpotifyRedirectIndex.get();
        YouTubeVideo video = youTubeService.getVideoForId(spotifyRedirectIndex.getYouTubeId());
        if (video != null) {
            try {
                youTubeVideo.setId(video.getVideoId());
                youTubeVideo.setDuration(video.getDuration());
            } catch (UnavailableResourceException e) {
                // never happens for YouTubeVideoImpl instances
                throw new RuntimeException(e);
            }
            youTubeVideo.setTitle(spotifyTrack.getDisplay());
            runUpdateTask(spotifyTrackId, (index, session) -> index.setLastUsed(LocalDate.now()));
            return;
        } else {
            runUpdateTask(spotifyTrackId, (index, session) -> session.delete(index));
        }
    }
    youTubeService.redirectSpotify(youTubeVideo);
    if (!youTubeVideo.isCanceled() && !Strings.isNullOrEmpty(spotifyTrack.getId())) {
        SINGE_THREAD_EXECUTOR_SERVICE.execute(() -> StaticSessionProvider.consumeSession(otherThreadSession -> {
            try {
                String videoId = youTubeVideo.getVideoId();
                SpotifyRedirectIndex spotifyRedirectIndex = new SpotifyRedirectIndex(spotifyTrack.getId(), videoId, spotifyTrack.getKind(), otherThreadSession);
                // check again if the index was not created by other thread
                if (queryExistingIndex(otherThreadSession, spotifyTrackId).isEmpty()) {
                    invoker.invoke(() -> otherThreadSession.persist(spotifyRedirectIndex));
                }
            } catch (UnavailableResourceException e) {
                logger.warn("Tried creating a SpotifyRedirectIndex for an unavailable Track");
            } catch (Exception e) {
                logger.error("Exception while creating SpotifyRedirectIndex", e);
            }
        }));
    }
}
Also used : Logger(org.slf4j.Logger) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) LoggerFactory(org.slf4j.LoggerFactory) Session(org.hibernate.Session) IOException(java.io.IOException) LoggingThreadFactory(net.robinfriedli.aiode.concurrent.LoggingThreadFactory) SpotifyRedirectIndex(net.robinfriedli.aiode.entities.SpotifyRedirectIndex) SpotifyRedirectIndexModificationLock(net.robinfriedli.aiode.entities.SpotifyRedirectIndexModificationLock) HibernateInvoker(net.robinfriedli.aiode.function.HibernateInvoker) Executors(java.util.concurrent.Executors) Aiode(net.robinfriedli.aiode.Aiode) Strings(com.google.common.base.Strings) HollowYouTubeVideo(net.robinfriedli.aiode.audio.youtube.HollowYouTubeVideo) LocalDate(java.time.LocalDate) BiConsumer(java.util.function.BiConsumer) Optional(java.util.Optional) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) StaticSessionProvider(net.robinfriedli.aiode.persist.StaticSessionProvider) ShutdownableExecutorService(net.robinfriedli.aiode.boot.ShutdownableExecutorService) ExecutorService(java.util.concurrent.ExecutorService) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService) SpotifyRedirectIndex(net.robinfriedli.aiode.entities.SpotifyRedirectIndex) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) HollowYouTubeVideo(net.robinfriedli.aiode.audio.youtube.HollowYouTubeVideo) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) IOException(java.io.IOException)

Example 3 with UnavailableResourceException

use of net.robinfriedli.aiode.exceptions.UnavailableResourceException in project aiode by robinfriedli.

the class AbstractPlayableLoadingCommand method loadYouTubeVideo.

private void loadYouTubeVideo(AudioManager audioManager) throws IOException {
    YouTubeService youTubeService = audioManager.getYouTubeService();
    if (argumentSet("select")) {
        int limit = getArgumentValueWithTypeOrElse("select", Integer.class, 10);
        List<YouTubeVideo> youTubeVideos = youTubeService.searchSeveralVideos(limit, getCommandInput());
        if (youTubeVideos.size() == 1) {
            Playable playable = youTubeVideos.get(0);
            handleResults(Lists.newArrayList(playable));
            loadedTrack = playable;
        } else if (youTubeVideos.isEmpty()) {
            throw new NoResultsFoundException(String.format("No YouTube video found for '%s'", getCommandInput()));
        } else {
            askQuestion(youTubeVideos, youTubeVideo -> {
                try {
                    return youTubeVideo.getDisplay();
                } catch (UnavailableResourceException e) {
                    // Unreachable since only HollowYouTubeVideos might get interrupted
                    throw new RuntimeException(e);
                }
            });
        }
    } else {
        YouTubeVideo youTubeVideo = youTubeService.searchVideo(getCommandInput());
        handleResults(Lists.newArrayList(youTubeVideo));
        loadedTrack = youTubeVideo;
    }
}
Also used : StringList(net.robinfriedli.stringlist.StringList) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) PlayableFactory(net.robinfriedli.aiode.audio.PlayableFactory) UrlPlayable(net.robinfriedli.aiode.audio.UrlPlayable) YouTubePlaylist(net.robinfriedli.aiode.audio.youtube.YouTubePlaylist) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Playable(net.robinfriedli.aiode.audio.Playable) Episode(se.michaelthelin.spotify.model_objects.specification.Episode) Callable(java.util.concurrent.Callable) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) Lists(com.google.common.collect.Lists) Playlist(net.robinfriedli.aiode.entities.Playlist) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) SearchEngine(net.robinfriedli.aiode.util.SearchEngine) Track(se.michaelthelin.spotify.model_objects.specification.Track) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) SpotifyUri(net.robinfriedli.aiode.audio.spotify.SpotifyUri) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) ArtistSimplified(se.michaelthelin.spotify.model_objects.specification.ArtistSimplified) CommandManager(net.robinfriedli.aiode.command.CommandManager) AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) IOException(java.io.IOException) AudioManager(net.robinfriedli.aiode.audio.AudioManager) NoSpotifyResultsFoundException(net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) UrlValidator(org.apache.commons.validator.routines.UrlValidator) Aiode(net.robinfriedli.aiode.Aiode) ShowSimplified(se.michaelthelin.spotify.model_objects.specification.ShowSimplified) List(java.util.List) AudioTrackLoader(net.robinfriedli.aiode.audio.AudioTrackLoader) SpotifyTrackResultHandler(net.robinfriedli.aiode.audio.spotify.SpotifyTrackResultHandler) SpotifyService(net.robinfriedli.aiode.audio.spotify.SpotifyService) CommandContext(net.robinfriedli.aiode.command.CommandContext) PlaylistSimplified(se.michaelthelin.spotify.model_objects.specification.PlaylistSimplified) AlbumSimplified(se.michaelthelin.spotify.model_objects.specification.AlbumSimplified) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) TrackLoadingExecutor(net.robinfriedli.aiode.audio.exec.TrackLoadingExecutor) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) UrlPlayable(net.robinfriedli.aiode.audio.UrlPlayable) Playable(net.robinfriedli.aiode.audio.Playable) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService)

Example 4 with UnavailableResourceException

use of net.robinfriedli.aiode.exceptions.UnavailableResourceException in project aiode by robinfriedli.

the class SearchCommand method searchYouTubeVideo.

private void searchYouTubeVideo() throws UnavailableResourceException, IOException {
    YouTubeService youTubeService = Aiode.get().getAudioManager().getYouTubeService();
    if (argumentSet("select")) {
        int limit = getArgumentValueWithTypeOrElse("select", Integer.class, 10);
        List<YouTubeVideo> youTubeVideos = youTubeService.searchSeveralVideos(limit, getCommandInput());
        if (youTubeVideos.size() == 1) {
            listYouTubeVideo(youTubeVideos.get(0));
        } else if (youTubeVideos.isEmpty()) {
            throw new NoResultsFoundException(String.format("No YouTube videos found for '%s'", getCommandInput()));
        } else {
            askQuestion(youTubeVideos, youTubeVideo -> {
                try {
                    return youTubeVideo.getDisplay();
                } catch (UnavailableResourceException e) {
                    // Unreachable since only HollowYouTubeVideos might get cancelled
                    throw new RuntimeException(e);
                }
            });
        }
    } else {
        listYouTubeVideo(youTubeService.searchVideo(getCommandInput()));
    }
}
Also used : PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) StringList(net.robinfriedli.stringlist.StringList) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) YouTubePlaylist(net.robinfriedli.aiode.audio.youtube.YouTubePlaylist) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Session(org.hibernate.Session) Episode(se.michaelthelin.spotify.model_objects.specification.Episode) Callable(java.util.concurrent.Callable) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) User(net.dv8tion.jda.api.entities.User) Util(net.robinfriedli.aiode.util.Util) Playlist(net.robinfriedli.aiode.entities.Playlist) AbstractSourceDecidingCommand(net.robinfriedli.aiode.command.commands.AbstractSourceDecidingCommand) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) SearchEngine(net.robinfriedli.aiode.util.SearchEngine) Track(se.michaelthelin.spotify.model_objects.specification.Track) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) ArtistSimplified(se.michaelthelin.spotify.model_objects.specification.ArtistSimplified) CommandManager(net.robinfriedli.aiode.command.CommandManager) Collection(java.util.Collection) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) NoSpotifyResultsFoundException(net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Aiode(net.robinfriedli.aiode.Aiode) ShowSimplified(se.michaelthelin.spotify.model_objects.specification.ShowSimplified) URLEncoder(java.net.URLEncoder) List(java.util.List) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) CommandContext(net.robinfriedli.aiode.command.CommandContext) PlaylistSimplified(se.michaelthelin.spotify.model_objects.specification.PlaylistSimplified) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) AlbumSimplified(se.michaelthelin.spotify.model_objects.specification.AlbumSimplified) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService)

Example 5 with UnavailableResourceException

use of net.robinfriedli.aiode.exceptions.UnavailableResourceException in project aiode by robinfriedli.

the class QueueIterator method playNext.

void playNext() {
    if (isReplaced) {
        return;
    }
    // don't skip over more than 10 items to avoid a frozen queue
    if (attemptCount.incrementAndGet() > 10) {
        MessageChannel communicationChannel = playback.getCommunicationChannel();
        if (communicationChannel != null) {
            EmbedBuilder embedBuilder = new EmbedBuilder();
            embedBuilder.setColor(Color.RED);
            embedBuilder.setDescription("Queue contains too many unplayable tracks subsequently for automatic skipping. You can skip to the next valid track manually.");
            messageService.sendTemporary(embedBuilder.build(), communicationChannel);
        }
        playback.stop();
        // reset just in case, even though the same QueueIterator instance will currently never be used again as the
        // user now either has to skip manually or start a new playback, creating a new iterator
        resetAttemptCount();
        return;
    }
    Playable track = queue.getCurrent();
    AudioItem result = null;
    AudioTrack cachedTracked = track.getCached();
    if (cachedTracked != null) {
        result = cachedTracked.makeClone();
    }
    if (result == null) {
        String playbackUrl;
        try {
            playbackUrl = track.getPlaybackUrl();
        } catch (UnavailableResourceException e) {
            iterateQueue(playback, queue, true);
            return;
        }
        try {
            result = audioTrackLoader.loadByIdentifier(playbackUrl);
        } catch (FriendlyException e) {
            sendError(track, e);
            iterateQueue(playback, queue, true);
            return;
        }
    }
    if (result != null) {
        if (result instanceof AudioTrack) {
            AudioTrack audioTrack = (AudioTrack) result;
            track.setCached(audioTrack);
            audioTrack.setUserData(track);
            playback.getAudioPlayer().playTrack(audioTrack);
            currentlyPlaying = track;
        } else {
            throw new UnsupportedOperationException("Expected an AudioTrack or Throwable but got " + result.getClass());
        }
    } else {
        iterateQueue(playback, queue);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException)

Aggregations

UnavailableResourceException (net.robinfriedli.aiode.exceptions.UnavailableResourceException)5 IOException (java.io.IOException)4 Aiode (net.robinfriedli.aiode.Aiode)3 YouTubeService (net.robinfriedli.aiode.audio.youtube.YouTubeService)3 YouTubeVideo (net.robinfriedli.aiode.audio.youtube.YouTubeVideo)3 AudioItem (com.sedmelluq.discord.lavaplayer.track.AudioItem)2 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)2 List (java.util.List)2 Callable (java.util.concurrent.Callable)2 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)2 SpotifyTrack (net.robinfriedli.aiode.audio.spotify.SpotifyTrack)2 YouTubePlaylist (net.robinfriedli.aiode.audio.youtube.YouTubePlaylist)2 CommandContext (net.robinfriedli.aiode.command.CommandContext)2 CommandManager (net.robinfriedli.aiode.command.CommandManager)2 Playlist (net.robinfriedli.aiode.entities.Playlist)2 CommandContribution (net.robinfriedli.aiode.entities.xml.CommandContribution)2 NoResultsFoundException (net.robinfriedli.aiode.exceptions.NoResultsFoundException)2 NoSpotifyResultsFoundException (net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException)2 SearchEngine (net.robinfriedli.aiode.util.SearchEngine)2 StringList (net.robinfriedli.stringlist.StringList)2