42 lines
1.4 KiB
C#
42 lines
1.4 KiB
C#
using IM_API.Dtos;
|
|
using IM_API.Interface.Services;
|
|
using IM_API.Tools;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using System.Security.Claims;
|
|
|
|
namespace IM_API.Hubs
|
|
{
|
|
public class ChatHub:Hub
|
|
{
|
|
private IMessageSevice _messageService;
|
|
public ChatHub(IMessageSevice messageService)
|
|
{
|
|
_messageService = messageService;
|
|
}
|
|
|
|
public async override Task OnConnectedAsync()
|
|
{
|
|
if (!Context.User.Identity.IsAuthenticated)
|
|
{
|
|
await Clients.Caller.SendAsync("ReceiveMessage",new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
|
|
Context.Abort();
|
|
return;
|
|
}
|
|
await base.OnConnectedAsync();
|
|
}
|
|
public async Task SendPrivateMessage(MessageBaseDto dto)
|
|
{
|
|
if (!Context.User.Identity.IsAuthenticated)
|
|
{
|
|
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
|
|
Context.Abort();
|
|
return;
|
|
}
|
|
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
await _messageService.SendPrivateMessageAsync(int.Parse(userIdStr),dto.ReceiverId,dto);
|
|
await Clients.Users(dto.ReceiverId.ToString()).SendAsync("ReceiveMessage", userIdStr, dto.Content);
|
|
return;
|
|
}
|
|
}
|
|
}
|