Selector/Selector.Event/CacheMappings/SpotifyMapping.cs

98 lines
3.2 KiB
C#
Raw Normal View History

using System.Text.Json;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using Selector.Cache;
namespace Selector.Events
{
public class SpotifyLinkChange
{
public string UserId { get; set; }
public bool PreviousLinkState { get; set; }
public bool NewLinkState { get; set; }
}
2021-12-20 23:04:53 +00:00
public partial class FromPubSub
{
2021-12-20 23:04:53 +00:00
public class SpotifyLink : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<SpotifyLink> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
2021-12-20 23:04:53 +00:00
public SpotifyLink(ILogger<SpotifyLink> logger,
ISubscriber subscriber,
UserEventBus userEvent)
{
Logger = logger;
Subscriber = subscriber;
UserEvent = userEvent;
}
2021-12-20 23:04:53 +00:00
public async Task ConstructMapping()
{
Logger.LogDebug("Forming Spotify link event mapping FROM cache TO event bus");
2021-12-20 23:04:53 +00:00
(await Subscriber.SubscribeAsync(Key.AllUserSpotify)).OnMessage(message => {
2021-12-20 23:04:53 +00:00
try
{
2021-12-20 23:04:53 +00:00
var userId = Key.Param(message.Channel);
var deserialised = JsonSerializer.Deserialize(message.Message, CacheJsonContext.Default.SpotifyLinkChange);
2021-12-20 23:04:53 +00:00
Logger.LogDebug("Received new Spotify link event for [{userId}]", deserialised.UserId);
if (!userId.Equals(deserialised.UserId))
{
Logger.LogWarning("Serialised user ID [{}] does not match cache channel [{}]", userId, deserialised.UserId);
}
UserEvent.OnSpotifyLinkChange(this, deserialised);
}
catch (TaskCanceledException)
{
Logger.LogDebug("Task Cancelled");
}
catch (Exception e)
{
Logger.LogError(e, "Error parsing new Spotify link event");
}
});
}
}
}
2021-12-20 23:04:53 +00:00
public partial class ToPubSub
{
2021-12-20 23:04:53 +00:00
public class SpotifyLink : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<SpotifyLink> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
2021-12-20 23:04:53 +00:00
public SpotifyLink(ILogger<SpotifyLink> logger,
ISubscriber subscriber,
UserEventBus userEvent)
{
Logger = logger;
Subscriber = subscriber;
UserEvent = userEvent;
}
2021-12-20 23:04:53 +00:00
public Task ConstructMapping()
{
2021-12-20 23:04:53 +00:00
Logger.LogDebug("Forming Spotify link event mapping TO cache FROM event bus");
UserEvent.SpotifyLinkChange += async (o, e) =>
{
var payload = JsonSerializer.Serialize(e, CacheJsonContext.Default.SpotifyLinkChange);
2021-12-20 23:04:53 +00:00
await Subscriber.PublishAsync(Key.UserSpotify(e.UserId), payload);
};
2021-12-20 23:04:53 +00:00
return Task.CompletedTask;
}
}
}
}