Search in sources :

Example 1 with SpotifyRedirectIndexModificationLock

use of net.robinfriedli.aiode.entities.SpotifyRedirectIndexModificationLock 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)

Aggregations

Stopwatch (com.google.common.base.Stopwatch)1 BigDecimal (java.math.BigDecimal)1 LocalDate (java.time.LocalDate)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 Aiode (net.robinfriedli.aiode.Aiode)1 SpotifyTrackBulkLoadingService (net.robinfriedli.aiode.audio.spotify.SpotifyTrackBulkLoadingService)1 SpotifyTrackKind (net.robinfriedli.aiode.audio.spotify.SpotifyTrackKind)1 YouTubeService (net.robinfriedli.aiode.audio.youtube.YouTubeService)1 SpotifyRedirectIndex (net.robinfriedli.aiode.entities.SpotifyRedirectIndex)1 SpotifyRedirectIndexModificationLock (net.robinfriedli.aiode.entities.SpotifyRedirectIndexModificationLock)1 LockOptions (org.hibernate.LockOptions)1 Session (org.hibernate.Session)1 SessionFactory (org.hibernate.SessionFactory)1 Transaction (org.hibernate.Transaction)1