Selector/Selector.CLI/DbWatcherService.cs

167 lines
6.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2021-10-28 23:05:07 +01:00
using Selector.Cache;
using Selector.Model;
using IF.Lastfm.Core.Api;
2021-10-28 23:05:07 +01:00
using StackExchange.Redis;
namespace Selector.CLI
{
class DbWatcherService : IHostedService
{
private const int PollPeriod = 1000;
2021-11-29 21:48:00 +00:00
private readonly ILogger<DbWatcherService> Logger;
private readonly IServiceProvider ServiceProvider;
private readonly IWatcherFactory WatcherFactory;
private readonly IWatcherCollectionFactory WatcherCollectionFactory;
private readonly IRefreshTokenFactoryProvider SpotifyFactory;
2021-10-28 23:05:07 +01:00
private readonly IAudioFeatureInjectorFactory AudioFeatureInjectorFactory;
private readonly IPlayCounterFactory PlayCounterFactory;
private readonly IPublisherFactory PublisherFactory;
private readonly ICacheWriterFactory CacheWriterFactory;
2021-10-11 23:19:19 +01:00
private Dictionary<string, IWatcherCollection> Watchers { get; set; } = new();
public DbWatcherService(
IWatcherFactory watcherFactory,
IWatcherCollectionFactory watcherCollectionFactory,
IRefreshTokenFactoryProvider spotifyFactory,
IAudioFeatureInjectorFactory audioFeatureInjectorFactory,
IPlayCounterFactory playCounterFactory,
2021-11-29 21:48:00 +00:00
ILogger<DbWatcherService> logger,
IServiceProvider serviceProvider,
IPublisherFactory publisherFactory = null,
ICacheWriterFactory cacheWriterFactory = null
)
{
2021-11-29 21:48:00 +00:00
Logger = logger;
ServiceProvider = serviceProvider;
WatcherFactory = watcherFactory;
WatcherCollectionFactory = watcherCollectionFactory;
SpotifyFactory = spotifyFactory;
AudioFeatureInjectorFactory = audioFeatureInjectorFactory;
PlayCounterFactory = playCounterFactory;
PublisherFactory = publisherFactory;
CacheWriterFactory = cacheWriterFactory;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("Starting database watcher service...");
var watcherIndices = await InitInstances();
2021-10-11 23:19:19 +01:00
Logger.LogInformation("Starting {count} affected watcher collection(s)...", watcherIndices.Count());
StartWatcherCollections(watcherIndices);
}
private async Task<IEnumerable<string>> InitInstances()
{
using var scope = ServiceProvider.CreateScope();
var db = scope.ServiceProvider.GetService<ApplicationDbContext>();
var indices = new HashSet<string>();
foreach (var dbWatcher in db.Watcher
.Include(w => w.User)
.Where(w => !string.IsNullOrWhiteSpace(w.User.SpotifyRefreshToken)))
{
Logger.LogInformation("Creating new [{type}] watcher", dbWatcher.Type);
var watcherCollectionIdx = dbWatcher.UserId;
indices.Add(watcherCollectionIdx);
if (!Watchers.ContainsKey(watcherCollectionIdx))
Watchers[watcherCollectionIdx] = WatcherCollectionFactory.Get();
var watcherCollection = Watchers[watcherCollectionIdx];
Logger.LogDebug("Getting Spotify factory");
var spotifyFactory = await SpotifyFactory.GetFactory(dbWatcher.User.SpotifyRefreshToken);
IWatcher watcher = null;
List<IConsumer> consumers = new();
switch (dbWatcher.Type)
{
case WatcherType.Player:
watcher = await WatcherFactory.Get<PlayerWatcher>(spotifyFactory, id: dbWatcher.UserId, pollPeriod: PollPeriod);
consumers.Add(await AudioFeatureInjectorFactory.Get(spotifyFactory));
if (CacheWriterFactory is not null) consumers.Add(await CacheWriterFactory.Get());
if (PublisherFactory is not null) consumers.Add(await PublisherFactory.Get());
if (!string.IsNullOrWhiteSpace(dbWatcher.User.LastFmUsername))
{
consumers.Add(await PlayCounterFactory.Get(creds: new() { Username = dbWatcher.User.LastFmUsername }));
}
else
{
Logger.LogDebug("[{username}] No Last.fm username, skipping play counter", dbWatcher.User.UserName);
}
break;
case WatcherType.Playlist:
throw new NotImplementedException("Playlist watchers not implemented");
2021-10-31 09:19:48 +00:00
// break;
}
watcherCollection.Add(watcher, consumers);
}
return indices;
}
private void StartWatcherCollections(IEnumerable<string> indices)
{
foreach (var index in indices)
{
try
{
Logger.LogInformation("Starting watcher collection [{index}]", index);
Watchers[index].Start();
}
catch (KeyNotFoundException)
{
Logger.LogError("Unable to retrieve watcher collection [{index}] when starting", index);
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("Shutting down");
2021-10-11 23:19:19 +01:00
foreach((var key, var watcher) in Watchers)
{
Logger.LogInformation("Stopping watcher collection [{key}]", key);
2021-10-11 23:19:19 +01:00
watcher.Stop();
}
return Task.CompletedTask;
}
}
}