Selector/Selector.Event/CacheMappings/NowPlayingMapping.cs

82 lines
2.6 KiB
C#
Raw Normal View History

using System.Text.Json;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using Selector.Cache;
namespace Selector.Events
{
2021-12-20 23:04:53 +00:00
public partial class FromPubSub
{
2021-12-20 23:04:53 +00:00
public class NowPlaying : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<NowPlaying> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
public NowPlaying(ILogger<NowPlaying> logger,
ISubscriber subscriber,
UserEventBus userEvent)
{
Logger = logger;
Subscriber = subscriber;
UserEvent = userEvent;
}
public async Task ConstructMapping()
{
Logger.LogDebug("Forming now playing event mapping between cache and event bus");
(await Subscriber.SubscribeAsync(Key.AllCurrentlyPlaying)).OnMessage(message => {
try
{
var userId = Key.Param(message.Channel);
var deserialised = JsonSerializer.Deserialize(message.Message, JsonContext.Default.CurrentlyPlayingDTO);
2021-12-20 23:04:53 +00:00
Logger.LogDebug("Received new currently playing [{username}]", deserialised.Username);
UserEvent.OnCurrentlyPlayingChange(this, deserialised);
2021-12-20 23:04:53 +00:00
}
catch (Exception e)
{
Logger.LogError(e, $"Error parsing new currently playing [{message}]");
}
});
}
}
2021-12-20 23:04:53 +00:00
}
2021-12-20 23:04:53 +00:00
public partial class ToPubSub
{
public class NowPlaying : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<NowPlaying> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
2021-12-20 23:04:53 +00:00
public NowPlaying(ILogger<NowPlaying> logger,
ISubscriber subscriber,
UserEventBus userEvent)
{
Logger = logger;
Subscriber = subscriber;
UserEvent = userEvent;
}
2021-12-20 23:04:53 +00:00
public Task ConstructMapping()
{
Logger.LogDebug("Forming now playing event mapping TO cache FROM event bus");
2021-12-20 23:04:53 +00:00
UserEvent.CurrentlyPlaying += async (o, e) =>
{
var payload = JsonSerializer.Serialize(e, JsonContext.Default.CurrentlyPlayingDTO);
await Subscriber.PublishAsync(Key.CurrentlyPlaying(e.UserId), payload);
2021-12-20 23:04:53 +00:00
};
return Task.CompletedTask;
}
}
}
}