58 lines
1.8 KiB
C#
58 lines
1.8 KiB
C#
using ConnectorService.Services;
|
|
using IM.Commons;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using StackExchange.Redis;
|
|
using System.Security.Claims;
|
|
|
|
namespace ConnectorService.Hubs
|
|
{
|
|
public class ChatHub : Hub
|
|
{
|
|
private readonly IConversationIntergrationService conService;
|
|
private readonly StackExchange.Redis.IDatabase redis;
|
|
private readonly ConnectionRegistry registry;
|
|
|
|
public ChatHub(IConversationIntergrationService conService, IConnectionMultiplexer multiplexer, ConnectionRegistry registry)
|
|
{
|
|
this.conService = conService;
|
|
this.redis = multiplexer.GetDatabase();
|
|
this.registry = registry;
|
|
}
|
|
|
|
public async override Task OnConnectedAsync()
|
|
{
|
|
if (!Context.User.Identity.IsAuthenticated)
|
|
{
|
|
Context.Abort();
|
|
return;
|
|
}
|
|
|
|
var userId = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
var res = await conService.GetUserStreamKeysAsync(Guid.Parse(userId));
|
|
foreach (var streamkey in res)
|
|
{
|
|
await Groups.AddToGroupAsync(Context.ConnectionId, streamkey);
|
|
}
|
|
|
|
await redis.SetAddAsync(RedisHelper.GetConnectionIdKey(userId), Context.ConnectionId);
|
|
await registry.Add(Context);
|
|
|
|
|
|
await base.OnConnectedAsync();
|
|
}
|
|
|
|
public async override Task OnDisconnectedAsync(Exception? exception)
|
|
{
|
|
await registry.Remove(Context);
|
|
if (Context.User.Identity.IsAuthenticated)
|
|
{
|
|
var userId = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
await redis.SetRemoveAsync(RedisHelper.GetConnectionIdKey(userId), Context.ConnectionId);
|
|
}
|
|
await base.OnDisconnectedAsync(exception);
|
|
}
|
|
}
|
|
}
|