IM/backend/IM_API/Hubs/ChatHub.cs
nanxun 58bc8b4b5a 前端:
1、优化消息排序逻辑
2、新增加载历史消息
3、修复已知问题
后端:
1、优化消息排序逻辑
2、增加用户信息缓存机制
3、修改日期类型为DateTimeOffset改善时区信息丢失问题
3、修复了已知问题
数据库:
1、新增SequenceId字段用于消息排序
2、新增ClientMsgId字段用于客户端消息回执
2026-02-07 22:37:56 +08:00

78 lines
3.1 KiB
C#

using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Message;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
namespace IM_API.Hubs
{
public class ChatHub:Hub
{
private IMessageSevice _messageService;
private readonly IConversationService _conversationService;
private readonly IEventBus _eventBus;
private readonly IMapper _mapper;
public ChatHub(IMessageSevice messageService, IConversationService conversationService, IEventBus eventBus, IMapper mapper)
{
_messageService = messageService;
_conversationService = conversationService;
_eventBus = eventBus;
_mapper = mapper;
}
public async override Task OnConnectedAsync()
{
if (!Context.User.Identity.IsAuthenticated)
{
Context.Abort();
return;
}
//将用户加入已加入聊天的会话组
string userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var keys = await _conversationService.GetUserAllStreamKeyAsync(int.Parse(userIdStr));
foreach(var key in keys)
{
await Groups.AddToGroupAsync(Context.ConnectionId,key);
}
await base.OnConnectedAsync();
}
public async Task<HubResponse<MessageBaseVo?>> SendMessage(MessageBaseDto dto)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<MessageBaseVo?>(CodeDefine.AUTH_FAILED, "SendMessage");
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
MessageBaseVo? msgInfo = null;
if(dto.ChatType == ChatType.PRIVATE)
{
msgInfo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
else
{
msgInfo = await _messageService.SendGroupMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
return new HubResponse<MessageBaseVo?>("SendMessage", msgInfo);
}
public async Task<HubResponse<object?>> ClearUnreadCount(int conversationId)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<object?>(CodeDefine.AUTH_FAILED, "ClearUnreadCount"); ;
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
await _conversationService.ClearUnreadCountAsync(int.Parse(userIdStr), conversationId);
return new HubResponse<object?>("ClearUnreadCount");
}
}
}