Selector/Selector.Web/Services/Mappings/NowPlayingMapping.cs

46 lines
1.6 KiB
C#
Raw Normal View History

2021-11-03 22:27:50 +00:00
using System;
using System.Text.Json;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using Selector.Web.Hubs;
using Selector.Cache;
namespace Selector.Web.Service
{
public class NowPlayingMapping : ICacheHubMapping<NowPlayingHub, INowPlayingHubClient>
{
2021-11-05 07:58:48 +00:00
private readonly ILogger<NowPlayingMapping> Logger;
2021-11-03 22:27:50 +00:00
private readonly string UserId;
2021-11-05 07:58:48 +00:00
private readonly string Username;
2021-11-03 22:27:50 +00:00
2021-11-05 07:58:48 +00:00
public NowPlayingMapping(ILogger<NowPlayingMapping> logger, string userId, string username)
2021-11-03 22:27:50 +00:00
{
2021-11-05 07:58:48 +00:00
Logger = logger;
2021-11-03 22:27:50 +00:00
UserId = userId;
2021-11-05 07:58:48 +00:00
Username = username;
2021-11-03 22:27:50 +00:00
}
public async Task ConstructMapping(ISubscriber subscriber, IHubContext<NowPlayingHub, INowPlayingHubClient> hub)
{
var key = Key.CurrentlyPlaying(UserId);
2021-11-05 07:58:48 +00:00
(await subscriber.SubscribeAsync(key)).OnMessage(async message => {
2021-11-03 22:27:50 +00:00
2021-11-05 07:58:48 +00:00
try{
var trimmedMessage = message.ToString().Substring(key.Length + 1);
var deserialised = JsonSerializer.Deserialize<CurrentlyPlayingDTO>(trimmedMessage);
Logger.LogDebug($"Received new currently playing [{deserialised.Username}] [{deserialised.Username}]");
await hub.Clients.User(UserId).OnNewPlaying(deserialised);
}
catch(Exception e)
{
Logger.LogError(e, $"Error parsing new currently playing [{message}]");
}
2021-11-03 22:27:50 +00:00
});
}
}
}