Selector/Selector.Event/CacheMappings/LastfmMapping.cs

94 lines
3.0 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 LastfmChange
{
public string UserId { get; set; }
public string PreviousUsername { get; set; }
public string NewUsername { get; set; }
}
2021-12-20 23:04:53 +00:00
public partial class FromPubSub
{
2021-12-20 23:04:53 +00:00
public class Lastfm : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<Lastfm> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
2021-12-20 23:04:53 +00:00
public Lastfm(ILogger<Lastfm> 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 Last.fm username event mapping FROM cache TO event bus");
2021-12-20 23:04:53 +00:00
(await Subscriber.SubscribeAsync(Key.AllUserLastfm)).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.LastfmChange);
2021-12-20 23:04:53 +00:00
Logger.LogDebug("Received new Last.fm username event for [{userId}]", deserialised.UserId);
if (!userId.Equals(deserialised.UserId))
{
Logger.LogWarning("Serialised user ID [{}] does not match cache channel [{}]", userId, deserialised.UserId);
}
UserEvent.OnLastfmCredChange(this, deserialised);
}
catch (Exception e)
{
Logger.LogError(e, "Error parsing Last.fm username event");
}
});
}
}
}
2021-12-20 23:04:53 +00:00
public partial class ToPubSub
{
2021-12-20 23:04:53 +00:00
public class Lastfm : IEventMapping
{
2021-12-20 23:04:53 +00:00
private readonly ILogger<Lastfm> Logger;
private readonly ISubscriber Subscriber;
private readonly UserEventBus UserEvent;
2021-12-20 23:04:53 +00:00
public Lastfm(ILogger<Lastfm> 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 Last.fm username event mapping TO cache FROM event bus");
UserEvent.LastfmCredChange += async (o, e) =>
{
var payload = JsonSerializer.Serialize(e, CacheJsonContext.Default.LastfmChange);
2021-12-20 23:04:53 +00:00
await Subscriber.PublishAsync(Key.UserLastfm(e.UserId), payload);
};
2021-12-20 23:04:53 +00:00
return Task.CompletedTask;
}
}
}
}