using NLog; using Sony.Filtr.SpotifyAnalytics; using System; using System.Threading.Tasks; using Sony.Filtr.Utility.Extensions; using System.Configuration; using Sony.Filtr.Utility; namespace Sony.Filtr.Tasks.Tasks.Spotify.Analytics { public class AggregatedPlaylistDataImportTask : IScheduledTask { private readonly PlaylistStreamsSummaryCalculator _playlistStreamsSummaryCalculator; private readonly SpotifyAnalyticsManager _spotifyAnalyticsManager; private readonly Logger _logger; public AggregatedPlaylistDataImportTask(SpotifyAnalyticsManager spotifyAnalyticsManager, PlaylistStreamsSummaryCalculator playlistStreamsSummaryCalculator) { this._playlistStreamsSummaryCalculator = playlistStreamsSummaryCalculator; this._spotifyAnalyticsManager = spotifyAnalyticsManager; _logger = LogManager.GetLogger("AggregatedPlaylistDataImportTask"); } private static bool AlwaysReprocess() { return Maybe.GetAppSettingsBooleanOrDefault("AggregatedPlaylistDataImportTask_Always_Reprocess", false); } public async Task ExecuteAsync(Guid scheduledTaskLogId) { bool shouldProcess = AlwaysReprocess(); this._logger.Info($"AlwaysReprocess: {shouldProcess}"); if (shouldProcess == false) { var previousLauncTime = ScheduledTaskLogFileParser.GetPreviousLaunchTime(); var latestUpdateTime = await this._spotifyAnalyticsManager.GetLatestTimestampWithDataAsync(); shouldProcess = previousLauncTime <= latestUpdateTime; this._logger.Info($"Should process: {shouldProcess}. Previous Launch Time: {previousLauncTime}. Latest Update Time: {latestUpdateTime}"); } if (shouldProcess) { try { await _playlistStreamsSummaryCalculator.SetPlaylistStreamsSummaryAsync(); } catch (Exception e) { _logger.Error(e); return new ScheduledTaskLog() { Finished = DateTimeOffset.UtcNow, Error = true, ErrorMessage = e.GetFullMessage() }; } } return new ScheduledTaskLog() { Finished = DateTimeOffset.UtcNow }; } } }