public async Task SendMessage(CreateMessageDto createMessageDto) { var username = Context.User.GetUsername(); if (username == createMessageDto.RecipientUsername.ToLower()) { throw new HubException("You cannot send messages to yourself"); } var sender = await _unitOfWork.UserRepository.GetUserByUsernameAsync(username); var recipient = await _unitOfWork.UserRepository.GetUserByUsernameAsync(createMessageDto.RecipientUsername); if (recipient == null) { throw new HubException("Not found user"); } var message = new Message { Sender = sender, Recipient = recipient, SenderUsername = sender.UserName, RecipientUsername = recipient.UserName, Content = createMessageDto.Content }; var groupName = GetGroupName(sender.UserName, recipient.UserName); var group = await _unitOfWork.MessageRepository.GetMessageGroup(groupName); if (group.Connections.Any(x => x.Username == recipient.UserName)) { message.DateRead = DateTime.UtcNow; } else { var connections = await _presenceTracker.GetConnectionsForUser(recipient.UserName); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewMessageRecieved", new { username = sender.UserName, knownAs = sender.KnownAs }); } } _unitOfWork.MessageRepository.AddMessage(message); if (await _unitOfWork.Complete()) { await Clients.Group(groupName).SendAsync("NewMessage", _mapper.Map <MessageDto>(message)); } }
/// <summary> /// WebSockets do not use HTTP and thus HTTP exceptions cannot be used /// </summary> public async Task SendMessage(MessageForCreationDto messageForCreationDto) { var userId = Context.User.GetUserId(); var sender = await _repo.GetUser(userId); messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { throw new HubException("Could not find user"); } var message = _mapper.Map <Message>(messageForCreationDto); var groupName = GetGroupName(sender.Username, recipient.Username); var group = await _repo.GetMessageGroup(groupName); if (group.Connections.Any(x => x.Username == recipient.Username)) { message.IsRead = true; message.DateRead = DateTime.UtcNow; } else { var connections = await _tracker.GetConnectionsForUser(recipient.Username); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewMessageReceived", new { id = sender.Id, knownAs = sender.KnownAs }); } } _repo.Add(message); if (await _repo.SaveAll()) { await Clients.Group(groupName).SendAsync("NewMessage", _mapper.Map <MessageToReturnDto>(message)); } }