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 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 SendMessage(MessageBaseDto dto) { if (!Context.User.Identity.IsAuthenticated) { await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse(CodeDefine.AUTH_FAILED)); Context.Abort(); return; } var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier); MessageBaseDto msgInfo = null; if(dto.ChatType.ToLower() == ChatType.PRIVATE.ToString().ToLower()) { msgInfo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto); } else { msgInfo = await _messageService.SendGroupMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto); } return; } } }