public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var usersSouled = await _repo.CheckUserSoul(userId, messageForCreationDto.RecipientId); if (!usersSouled && sender.Id != recipient.Id) { return(Unauthorized()); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId = userId, id = message.Id }, messageToReturn)); } throw new Exception("Failed to send the message"); }
public async Task <string> SendMessage(int userId, int recipientId, string content, string hubConnectionId) { var messageForCreationDto = new MessageForCreationDto { RecipientId = recipientId, Content = content }; var sender = await _repo.GetUser(userId); if (sender == null) { throw new Exception("Unauthorize"); } List <string> existingUserConnectionIds; MyUsers.TryGetValue(messageForCreationDto.RecipientId, out existingUserConnectionIds); if (sender.Id != int.Parse(_contextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value)) { throw new Exception("Unauthorize"); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { throw new Exception("User no longer exist"); } if (await _repo.CheckUserSoul(messageForCreationDto.SenderId, messageForCreationDto.RecipientId) == false) { throw new Exception("Unauthorize"); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { MyUsers.TryGetValue(messageForCreationDto.SenderId, out existingUserConnectionIds); if (userId != recipientId) { if (await EmitMessageToUser(message.SenderId, message.RecipientId, message.Id, message.Content, message.SentDate)) { await Clients.Clients(existingUserConnectionIds).SendAsync("messageReceived", recipientId, message.Id, message.SentDate, message.Content, true, hubConnectionId); } else { await Clients.Clients(existingUserConnectionIds).SendAsync("messageReceived", recipientId, message.Id, message.SentDate, message.Content, false, hubConnectionId); } } return(message.SentDate.ToString() + '-' + message.Id); } throw new Exception("Failed to send the message"); }