2021-11-10 01:46:30 +00:00
|
|
|
using System;
|
|
|
|
using System.Text.Json;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using SpotifyAPI.Web;
|
|
|
|
using StackExchange.Redis;
|
|
|
|
|
|
|
|
namespace Selector.Cache
|
|
|
|
{
|
|
|
|
public class AudioFeaturePuller
|
|
|
|
{
|
|
|
|
private readonly IRefreshTokenFactoryProvider SpotifyFactory;
|
|
|
|
private readonly IDatabaseAsync Cache;
|
|
|
|
|
|
|
|
public AudioFeaturePuller(
|
|
|
|
IRefreshTokenFactoryProvider spotifyFactory,
|
2021-12-04 12:49:09 +00:00
|
|
|
IDatabaseAsync cache = null
|
2021-11-10 01:46:30 +00:00
|
|
|
)
|
|
|
|
{
|
|
|
|
SpotifyFactory = spotifyFactory;
|
|
|
|
Cache = cache;
|
|
|
|
}
|
|
|
|
|
2021-11-10 23:54:28 +00:00
|
|
|
public async Task<TrackAudioFeatures> Get(string refreshToken, string trackId)
|
2021-11-10 01:46:30 +00:00
|
|
|
{
|
2021-11-10 23:54:28 +00:00
|
|
|
if(string.IsNullOrWhiteSpace(trackId)) throw new ArgumentNullException("No track Id provided");
|
|
|
|
|
2021-12-04 12:49:09 +00:00
|
|
|
var track = await Cache?.StringGetAsync(Key.AudioFeature(trackId));
|
|
|
|
if (Cache is null || track == RedisValue.Null)
|
2021-11-10 01:46:30 +00:00
|
|
|
{
|
2021-11-10 23:54:28 +00:00
|
|
|
if(!string.IsNullOrWhiteSpace(refreshToken))
|
|
|
|
{
|
|
|
|
var factory = await SpotifyFactory.GetFactory(refreshToken);
|
|
|
|
var spotifyClient = new SpotifyClient(await factory.GetConfig());
|
|
|
|
|
|
|
|
// TODO: Error checking
|
|
|
|
return await spotifyClient.Tracks.GetAudioFeatures(trackId);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
2021-11-10 01:46:30 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2021-12-21 22:22:52 +00:00
|
|
|
var deserialised = JsonSerializer.Deserialize(track, JsonContext.Default.TrackAudioFeatures);
|
2021-11-10 01:46:30 +00:00
|
|
|
return deserialised;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|