#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace gehGassi.Web.Hubs
{
///
/// Hub der App-Nachrichten ermöglicht
///
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class AppHub : Hub, IAppHub
{
private readonly IHubContext _hubContext;
private readonly IAppHubUsers _appHubUsers;
///
/// Erstellt eine Instanz
///
public AppHub(IHubContext hubContext, IAppHubUsers appHubUsers) : base()
{
_hubContext = hubContext;
_appHubUsers = appHubUsers;
}
#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;
_appHubUsers.ConnectedUsers.TryGetValue(userName, out var existingUserConnectionIds);
existingUserConnectionIds ??= new List();
existingUserConnectionIds.Add(Context.ConnectionId);
_appHubUsers.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;
_appHubUsers.ConnectedUsers.TryGetValue(userName, out var existingUserConnectionIds);
existingUserConnectionIds?.Remove(Context.ConnectionId);
if (existingUserConnectionIds != null && existingUserConnectionIds.Count == 0)
{
_appHubUsers.ConnectedUsers.TryRemove(userName, out var garbage);
}
}
return base.OnDisconnectedAsync(exception);
}
#endregion
///
/// Buchen der Events eines App-Users
///
/// ID des App-Users
/// Task
public async Task JoinAppUser(string appUserId)
{
var group = $"appuser_{appUserId}";
await _hubContext.Groups.AddToGroupAsync(Context.ConnectionId, group);
}
///
/// Abbsestellen der Events eines App-Users
///
/// ID des App-Users
/// Task
public async Task LeaveAppUser(string appUserId)
{
var group = $"appuser_{appUserId}";
await _hubContext.Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
}
///
/// Buchen der Events einer Konversation für einen Benutzer
///
/// Id der Konversation
/// ID des App-Users
/// Task
public async Task JoinConversation(string conversationId, string appUserId)
{
var group = $"conversation_{conversationId}_{appUserId}";
await _hubContext.Groups.AddToGroupAsync(Context.ConnectionId, group);
}
///
/// Abbsestellen der Events einer Konversation
///
/// Id der Konversation
/// ID des App-Users
/// Task
public async Task LeaveConversation(string conversationId, string appUserId)
{
var group = $"conversation_{conversationId}_{appUserId}";
await _hubContext.Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
}
}
}