sozsoft-platform/api/src/Sozsoft.Platform.Application/Messenger/MessengerHub.cs
2026-06-26 01:55:44 +03:00

84 lines
2.4 KiB
C#

#nullable enable
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Users;
namespace Sozsoft.Platform.Messenger;
[Authorize]
public class MessengerHub : Hub
{
private readonly ICurrentTenant _currentTenant;
private readonly ICurrentUser _currentUser;
private readonly MessengerAppService _messengerAppService;
public MessengerHub(
ICurrentTenant currentTenant,
ICurrentUser currentUser,
MessengerAppService messengerAppService)
{
_currentTenant = currentTenant;
_currentUser = currentUser;
_messengerAppService = messengerAppService;
}
public override async Task OnConnectedAsync()
{
if (_currentUser.Id.HasValue)
{
await Groups.AddToGroupAsync(Context.ConnectionId, UserGroupName(_currentUser.Id.Value));
await Groups.AddToGroupAsync(Context.ConnectionId, TenantGroupName());
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
if (_currentUser.Id.HasValue)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, UserGroupName(_currentUser.Id.Value));
await Groups.RemoveFromGroupAsync(Context.ConnectionId, TenantGroupName());
}
await base.OnDisconnectedAsync(exception);
}
public async Task SendMessage(MessengerSendMessageDto input)
{
try
{
await _messengerAppService.SendMessageAsync(input);
}
catch (OperationCanceledException) when (Context.ConnectionAborted.IsCancellationRequested)
{
return;
}
}
public async Task DeleteMessage(Guid messageId)
{
try
{
await _messengerAppService.DeleteMessageAsync(messageId);
}
catch (OperationCanceledException) when (Context.ConnectionAborted.IsCancellationRequested)
{
return;
}
}
private string TenantKey => _currentTenant.Id?.ToString("N") ?? "host";
private string TenantGroupName() => $"messenger:tenant:{TenantKey}";
public static string UserGroupName(Guid? tenantId, Guid userId) =>
$"messenger:user:{tenantId?.ToString("N") ?? "host"}:{userId:N}";
private string UserGroupName(Guid userId) => UserGroupName(_currentTenant.Id, userId);
}