81 lines
2.8 KiB
C#
81 lines
2.8 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
|
|
namespace gehGassi.Web.Hubs
|
|
{
|
|
/// <summary>
|
|
/// Hub der Systemnachrichten ermöglicht
|
|
/// </summary>
|
|
[Authorize]
|
|
public class SystemHub : Hub, ISystemHub
|
|
{
|
|
private readonly IHubContext<SystemHub> _hubContext;
|
|
private readonly ISystemHubUsers _systemHubUsers;
|
|
|
|
/// <summary>
|
|
/// Erstellt eine Instanz
|
|
/// </summary>
|
|
public SystemHub(IHubContext<SystemHub> hubContext, ISystemHubUsers systemHubUsers) : base()
|
|
{
|
|
_hubContext = hubContext;
|
|
_systemHubUsers = systemHubUsers;
|
|
}
|
|
|
|
#region Benutzer
|
|
|
|
/// <summary>
|
|
/// Called when a new connection is established with the hub.
|
|
/// </summary>
|
|
/// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous connect.</returns>
|
|
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<string>();
|
|
existingUserConnectionIds.Add(Context.ConnectionId);
|
|
_systemHubUsers.ConnectedUsers.TryAdd(userName, existingUserConnectionIds);
|
|
}
|
|
|
|
return base.OnConnectedAsync();
|
|
}
|
|
|
|
/// <summary>Called when a connection with the hub is terminated.</summary>
|
|
/// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous disconnect.</returns>
|
|
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
|
|
|
|
|
|
/// <summary>
|
|
/// Buchen der Events eines Kunden
|
|
/// </summary>
|
|
/// <param name="customerId">ID des Kunden</param>
|
|
/// <returns>Task</returns>
|
|
public async Task JoinCustomer(Guid customerId)
|
|
{
|
|
var group = $"customer_{customerId}";
|
|
await _hubContext.Groups.AddToGroupAsync(Context.ConnectionId, group);
|
|
}
|
|
}
|
|
}
|