#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace gehGassi.Web.Hubs
{
///
/// Hub der Systemnachrichten ermöglicht
///
[Authorize]
public class SystemHub : Hub, ISystemHub
{
private readonly IHubContext _hubContext;
private readonly ISystemHubUsers _systemHubUsers;
///
/// Erstellt eine Instanz
///
public SystemHub(IHubContext hubContext, ISystemHubUsers systemHubUsers) : base()
{
_hubContext = hubContext;
_systemHubUsers = systemHubUsers;
}
#region Benutzer
///
/// Called when a new connection is established with the hub.
///
/// A that represents the asynchronous connect.
public override Task OnConnectedAsync()
{
if (Context.User?.Identity != null)
{
var userName = Context.User.Identity.Name;
_systemHubUsers.ConnectedUsers.TryGetValue(userName, out var existingUserConnectionIds);
existingUserConnectionIds ??= new List();
existingUserConnectionIds.Add(Context.ConnectionId);
_systemHubUsers.ConnectedUsers.TryAdd(userName, existingUserConnectionIds);
}
return base.OnConnectedAsync();
}
/// Called when a connection with the hub is terminated.
/// A that represents the asynchronous disconnect.
public override Task OnDisconnectedAsync(Exception? exception)
{
if (Context.User?.Identity != null)
{
var userName = Context.User.Identity.Name;
_systemHubUsers.ConnectedUsers.TryGetValue(userName, out var existingUserConnectionIds);
existingUserConnectionIds?.Remove(Context.ConnectionId);
if (existingUserConnectionIds != null && existingUserConnectionIds.Count == 0)
{
_systemHubUsers.ConnectedUsers.TryRemove(userName, out var garbage);
}
}
return base.OnDisconnectedAsync(exception);
}
#endregion
///
/// Buchen der Events eines Kunden
///
/// ID des Kunden
/// Task
public async Task JoinCustomer(Guid customerId)
{
var group = $"customer_{customerId}";
await _hubContext.Groups.AddToGroupAsync(Context.ConnectionId, group);
}
}
}