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();
}
}
}
}
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");
}
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()));
}
}
Aggregations