sozsoft-platform/api/src/Sozsoft.Platform.Application/Messenger/MessengerHub.cs

84 lines
2.5 KiB
C#
Raw Normal View History

2026-06-12 17:31:41 +00:00
#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;
2026-06-12 19:35:48 +00:00
private readonly MessengerAppService _messengerAppService;
2026-06-12 17:31:41 +00:00
public MessengerHub(
ICurrentTenant currentTenant,
ICurrentUser currentUser,
2026-06-12 19:35:48 +00:00
MessengerAppService messengerAppService)
2026-06-12 17:31:41 +00:00
{
_currentTenant = currentTenant;
_currentUser = currentUser;
2026-06-12 19:35:48 +00:00
_messengerAppService = messengerAppService;
2026-06-12 17:31:41 +00:00
}
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)
{
2026-06-12 19:35:48 +00:00
var message = await _messengerAppService.SendMessageAsync(input);
2026-06-12 17:31:41 +00:00
2026-06-12 19:35:48 +00:00
var targetGroups = message.RecipientIds
.Append(message.SenderId)
2026-06-12 17:31:41 +00:00
.Distinct()
2026-06-12 19:35:48 +00:00
.Select(UserGroupName)
2026-06-12 17:31:41 +00:00
.ToList();
2026-06-12 19:35:48 +00:00
await Clients.Groups(targetGroups).SendAsync("MessengerMessageReceived", message);
}
2026-06-12 17:31:41 +00:00
2026-06-12 19:35:48 +00:00
public async Task DeleteMessage(Guid messageId)
{
var deletedMessage = await _messengerAppService.DeleteMessageAsync(messageId);
2026-06-12 17:31:41 +00:00
2026-06-12 19:35:48 +00:00
var targetGroups = deletedMessage.RecipientIds
.Append(deletedMessage.SenderId)
2026-06-12 17:31:41 +00:00
.Distinct()
.Select(UserGroupName)
.ToList();
2026-06-12 19:35:48 +00:00
await Clients.Groups(targetGroups).SendAsync("MessengerMessageDeleted", deletedMessage);
2026-06-12 17:31:41 +00:00
}
private string TenantKey => _currentTenant.Id?.ToString("N") ?? "host";
private string TenantGroupName() => $"messenger:tenant:{TenantKey}";
private string UserGroupName(Guid userId) => $"messenger:user:{TenantKey}:{userId:N}";
}