Search in sources :

Example 6 with YouTubeService

use of net.robinfriedli.aiode.audio.youtube.YouTubeService in project aiode by robinfriedli.

the class RefreshSpotifyRedirectIndicesTask method run.

@Override
protected void run(JobExecutionContext jobExecutionContext) {
    logger.info("Starting SpotifyRedirectIndex refresh");
    SessionFactory sessionFactory = StaticSessionProvider.getSessionFactory();
    SpotifyRedirectIndexModificationLock spotifyRedirectIndexModificationLock = new SpotifyRedirectIndexModificationLock();
    spotifyRedirectIndexModificationLock.setCreationTimeStamp(LocalDateTime.now());
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        session.persist(spotifyRedirectIndexModificationLock);
        transaction.commit();
    }
    try {
        Aiode aiode = Aiode.get();
        Stopwatch stopwatch = Stopwatch.createStarted();
        YouTubeService youTubeService = aiode.getAudioManager().getYouTubeService();
        SpotifyTrackBulkLoadingService spotifyTrackBulkLoadingService = new SpotifyTrackBulkLoadingService(spotifyApi, true);
        LocalDate currentDate = LocalDate.now();
        LocalDate date4WeeksAgo = currentDate.minusDays(28);
        StaticSessionProvider.consumeSession(session -> {
            CriteriaBuilder cb = session.getCriteriaBuilder();
            CriteriaQuery<SpotifyRedirectIndex> query = cb.createQuery(SpotifyRedirectIndex.class);
            Root<SpotifyRedirectIndex> root = query.from(SpotifyRedirectIndex.class);
            query.where(cb.lessThan(root.get("lastUpdated"), date4WeeksAgo));
            query.orderBy(cb.asc(root.get("lastUpdated")));
            List<SpotifyRedirectIndex> indices = session.createQuery(query).setLockOptions(new LockOptions(LockMode.PESSIMISTIC_WRITE)).getResultList();
            if (indices.isEmpty()) {
                return;
            }
            BigDecimal averageDailyIndices = (BigDecimal) session.createSQLQuery("select avg(count) from (select count(*) as count from spotify_redirect_index group by last_updated) as sub").uniqueResult();
            int average = averageDailyIndices.setScale(0, RoundingMode.CEILING).intValue();
            int updateCount = 0;
            for (SpotifyRedirectIndex index : indices) {
                SpotifyTrackKind kind = index.getSpotifyItemKind().asEnum();
                RefreshTrackIndexTask task = new RefreshTrackIndexTask(session, index, youTubeService);
                String spotifyId = index.getSpotifyId();
                if (!Strings.isNullOrEmpty(spotifyId)) {
                    spotifyTrackBulkLoadingService.add(createItem(spotifyId, kind), task);
                } else {
                    session.delete(index);
                }
                ++updateCount;
                if (updateCount == average) {
                    break;
                }
            }
            spotifyTrackBulkLoadingService.perform();
            stopwatch.stop();
            logger.info(String.format("Regenerated %d spotify redirect indices in %d seconds", updateCount, stopwatch.elapsed(TimeUnit.SECONDS)));
        });
    } finally {
        Transaction transaction = null;
        try (Session session = sessionFactory.openSession()) {
            transaction = session.beginTransaction();
            // since hibernate is now bootstrapped by JPA rather than native after implementing spring boot
            // the entity has the be merged because JPA does not allow the deletion of detached entities
            Object merge = session.merge(spotifyRedirectIndexModificationLock);
            session.delete(merge);
            transaction.commit();
        } catch (Throwable e) {
            // catch exceptions thrown in the finally block so as to not override exceptions thrown in the try block
            logger.error("Exception thrown while deleting SpotifyRedirectIndexModificationLock", e);
            if (transaction != null) {
                transaction.rollback();
            }
        }
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) LockOptions(org.hibernate.LockOptions) SpotifyRedirectIndex(net.robinfriedli.aiode.entities.SpotifyRedirectIndex) Stopwatch(com.google.common.base.Stopwatch) SpotifyRedirectIndexModificationLock(net.robinfriedli.aiode.entities.SpotifyRedirectIndexModificationLock) Aiode(net.robinfriedli.aiode.Aiode) LocalDate(java.time.LocalDate) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService) BigDecimal(java.math.BigDecimal) Transaction(org.hibernate.Transaction) SpotifyTrackBulkLoadingService(net.robinfriedli.aiode.audio.spotify.SpotifyTrackBulkLoadingService) SpotifyTrackKind(net.robinfriedli.aiode.audio.spotify.SpotifyTrackKind) Session(org.hibernate.Session)

Example 7 with YouTubeService

use of net.robinfriedli.aiode.audio.youtube.YouTubeService in project aiode by robinfriedli.

the class ResetCurrentYouTubeQuotaTask method run.

@Override
protected void run(JobExecutionContext jobExecutionContext) {
    YouTubeService youTubeService = Aiode.get().getAudioManager().getYouTubeService();
    StaticSessionProvider.consumeSession(session -> {
        CurrentYouTubeQuotaUsage currentQuotaUsage = YouTubeService.getCurrentQuotaUsage(session, LockModeType.PESSIMISTIC_WRITE);
        youTubeService.setAtomicQuotaUsage(0);
        currentQuotaUsage.setQuota(0);
    });
    LoggerFactory.getLogger(getClass()).info("Reset current YouTube API Quota counter");
}
Also used : CurrentYouTubeQuotaUsage(net.robinfriedli.aiode.entities.CurrentYouTubeQuotaUsage) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService)

Example 8 with YouTubeService

use of net.robinfriedli.aiode.audio.youtube.YouTubeService 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)

Aggregations

YouTubeService (net.robinfriedli.aiode.audio.youtube.YouTubeService)8 YouTubePlaylist (net.robinfriedli.aiode.audio.youtube.YouTubePlaylist)4 NoResultsFoundException (net.robinfriedli.aiode.exceptions.NoResultsFoundException)4 Aiode (net.robinfriedli.aiode.Aiode)3 Playable (net.robinfriedli.aiode.audio.Playable)3 SpotifyTrack (net.robinfriedli.aiode.audio.spotify.SpotifyTrack)3 IOException (java.io.IOException)2 List (java.util.List)2 Callable (java.util.concurrent.Callable)2 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)2 PlayableFactory (net.robinfriedli.aiode.audio.PlayableFactory)2 UrlPlayable (net.robinfriedli.aiode.audio.UrlPlayable)2 YouTubeVideo (net.robinfriedli.aiode.audio.youtube.YouTubeVideo)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 NoSpotifyResultsFoundException (net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException)2 UnavailableResourceException (net.robinfriedli.aiode.exceptions.UnavailableResourceException)2 SearchEngine (net.robinfriedli.aiode.util.SearchEngine)2