Selector/Selector.Cache/Consumer/AudioInjectorCaching.cs

48 lines
1.4 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SpotifyAPI.Web;
using StackExchange.Redis;
namespace Selector.Cache
{
public class CachingAudioFeatureInjector : AudioFeatureInjector
{
private readonly IDatabaseAsync Db;
2021-11-11 19:54:28 +00:00
public TimeSpan CacheExpiry { get; set; } = TimeSpan.FromDays(14);
public CachingAudioFeatureInjector(
IPlayerWatcher watcher,
IDatabaseAsync db,
ITracksClient trackClient,
ILogger<CachingAudioFeatureInjector> logger = null,
CancellationToken token = default
) : base(watcher, trackClient, logger, token) {
Db = db;
NewFeature += CacheCallback;
}
public void CacheCallback(object sender, AnalysedTrack e)
{
Task.Run(async () => { await AsyncCacheCallback(e); }, CancelToken);
}
public async Task AsyncCacheCallback(AnalysedTrack e)
{
var payload = JsonSerializer.Serialize(e.Features);
Logger.LogTrace($"Caching current for [{e.Track.DisplayString()}]");
var resp = await Db.StringSetAsync(Key.AudioFeature(e.Track.Id), payload, expiry: CacheExpiry);
Logger.LogDebug($"Cached audio feature for [{e.Track.DisplayString()}], {(resp ? "value set" : "value NOT set")}");
}
}
}