Beispiel #1
0
        public async Task SendMessage(CreateMessageDto createMessageDto)
        {
            var userName = Context.User.GetUserName();

            if (userName == createMessageDto.RecipientUserName.ToLower())
            {
                throw new Exception("You can't send message to yourself");
            }

            var recipient = await _unitOfWork.UserRepository.GetUserByNameAsync(createMessageDto.RecipientUserName);

            var sender = await _unitOfWork.UserRepository.GetUserByNameAsync(userName);

            if (recipient == null)
            {
                throw new Exception("User not found");
            }

            var message = new Message
            {
                SenderId          = sender.Id,
                SenderUserName    = sender.UserName,
                RecipientId       = recipient.Id,
                RecipientUserName = recipient.UserName,
                Content           = createMessageDto.Content
            };

            var groupName = GetGroupName(message.SenderUserName, message.RecipientUserName);

            var group = await _unitOfWork.MessageRepository.GetMessageGroup(groupName);

            if (group.Connections.Any(x => x.userName == recipient.UserName))
            {
                message.DateRead = DateTime.UtcNow;
            }
            else
            {
                var connectionIds = await _presenceTracker.GetConnectionIds(recipient.UserName);

                if (connectionIds != null)
                {
                    await _presenceHub.Clients.Clients(connectionIds).SendAsync("NewMessageReceived", new
                    {
                        userName = sender.UserName,
                        nickName = sender.NickName
                    });
                }
            }

            _unitOfWork.MessageRepository.AddMessage(message);

            if (await _unitOfWork.SaveChanges())
            {
                await Clients.Group(groupName).SendAsync("NewMessage", _mapper.Map <MessageDto>(message));
            }
        }