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 message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id, userid = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) }, messageToReturn)); } throw new Exception("Creating the message filed on save"); }
public Message MapCreatedMessage(MessageForCreationDto messageForCreation) { var message = _mapper.Map <Message>(messageForCreation); _genericsRepo.Add(message); return(message); }
public async Task <IActionResult> CreateMessage([FromBody] MessageForCreationDto messageDto) { var message = await _service.SaveMessage(base.GetUserIdFromToken(), messageDto); var currentMessage = await _service.GetMessage(message.Id); return(Ok(_mapper.To <MessageToReturnDto>(currentMessage))); }
public async Task <CreatedAtActionResult> CreateMessage(MessageForCreationDto messageForCreationDto) { var userId = HttpContext.GetUserId(); var messageDto = await _messageService.CreateMessage(userId, messageForCreationDto); return(CreatedAtAction(nameof(GetMessage), new { id = messageDto.Id }, messageDto)); }
public async Task <IActionResult> Index(MessageForCreationDto messageForCreationDto) { var messageForSend = await CreateMessageForSend(messageForCreationDto.message); await LogInformation(messageForCreationDto.ToString()); var response = await _telegramRequest.SendMessage(messageForSend); return(StatusCode(201)); }
public ActionResult <MessageDto> CreateMessage(MessageForCreationDto message) { var messageEntity = _mapper.Map <Entities.Message>(message); _messageBoardRepository.AddMessage(messageEntity); _messageBoardRepository.Save(); var messageToReturn = _mapper.Map <MessageDto>(messageEntity); return(CreatedAtRoute("GetMessage", new { messageId = messageToReturn.Id }, messageToReturn)); }
public async void SendGlobalMessage(MessageForCreationDto messageForCreationDto) { var userId = int.Parse(Context.User.FindFirst(ClaimTypes.NameIdentifier).Value); var sender = context.Users.FirstOrDefault(u => u.Id == userId); var messageToReturn = mapper.Map <MessageToReturnDto>(messageForCreationDto); messageToReturn.SenderUsername = sender.UserName; messageToReturn.SenderPhotoUrl = sender.PhotoUrl; messageToReturn.SenderId = userId; await Clients.All.NewGlobalMessage(messageToReturn); }
public void SendPrivateMessage(string senderId, MessageForCreationDto messageForCreationDto) { messageForCreationDto.SenderId = int.Parse(senderId); var message = _mapper.Map <Message>(messageForCreationDto); //_repo.Add(message); //_repo.SaveAll(); Clients.User(ClaimTypes.Name).SendAsync("sendPrivately", message); }
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 message = _mapper.Map <Message>(messageForCreationDto); var messageSnippet = message.Content; if (messageSnippet.Length > 60) { messageSnippet = messageSnippet.Remove(57).TrimEnd() + "..."; } if (await _repo.Add(message)) { try { await _mailer.SendMessagedMail( new MailUser { Email = recipient.Email, Name = recipient.Name }, sender.Name, messageSnippet ); } catch (Exception) { return(BadRequest("Successfully sent message, Unable to send email")); } var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
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 receiver = await _repo.GetUser(messageForCreationDto.ReceiverId); if (receiver == null) { return(BadRequest("User not found")); } var message = _mapper.Map <Message>(messageForCreationDto); var like = await _repo.GetLike(userId, receiver.Id); var reverseLike = await _repo.GetLike(receiver.Id, userId); if (like == null && reverseLike == null) { return(BadRequest("Cannot message without a match")); } if (like != null) { if (like.Match == false) { return(BadRequest("Cannot message without a match")); } } if (reverseLike != null) { if (reverseLike.Match == false) { return(BadRequest("Cannot message without a match")); } } _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageForCreationDto>(message); return(CreatedAtRoute(nameof(GetMessage), new { userId = userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
private async Task SendNotification(int userId, string emailContent) { var messageForCreationDto = new MessageForCreationDto() { RecipientId = userId, SenderId = userId, Content = emailContent }; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Message.AddMessage(message); await _repo.Message.SaveAllAsync(); }
private async Task SendNotificationsForSubordinate(int userId, string emailContent, List <int> sheetOwnerIds) { foreach (var sheetOwnerId in sheetOwnerIds) { var messageForCreationDto = new MessageForCreationDto() { RecipientId = sheetOwnerId, SenderId = userId, Content = emailContent }; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Message.AddMessage(message); } await _repo.Message.SaveAllAsync(); }
public IActionResult SendMessage(Guid petId, Guid messageBoxId, MessageForCreationDto messageDto) { var messageBox = _unitOfWork.Messages.GetBox(petId, messageBoxId, Account.Id); if (messageBox == null) { throw new KeyNotFoundException("Message box not found"); } var message = new Message(messageDto.Body, Account.Id, messageBox); _unitOfWork.Messages.Add(message); _unitOfWork.Complete(); return(new AcceptedResult()); }
/* ************* */ public async Task SendMessage(int id, MessageForCreationDto createMessageDto) { var username = Context.User.FindFirst(ClaimTypes.Name)?.Value; var usernameId = int.Parse(Context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value); if (usernameId == createMessageDto.RecipientId) { throw new HubException("You cannot send messages to yourself"); } var sender = await _messageReop.GetUser(usernameId, false); var recipient = await _messageReop.GetUser(createMessageDto.RecipientId, false); if (recipient == null) { throw new HubException("Not found user"); } var message = new Message { RecipientId = recipient.Id, SenderId = sender.Id, Content = createMessageDto.Content }; var groupName = GetGroupName(sender.UserName, recipient.UserName); var group = await _messageReop.GetMessageGroup(groupName); if (group.Connection.Any(x => x.UserName == recipient.UserName)) { message.DateRead = DateTime.UtcNow; } else { } _messageReop.Add(message); if (await _messageReop.SaveAll()) { await Clients.Group(groupName).SendAsync("NewMessage", _mapper.Map <MessageToReturnDto>(message)); } }
public async Task <IActionResult> GetMessage(int userId, int id) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } Message messageFromRepo = await _repo.GetMessage(id); if (messageFromRepo == null) { return(NotFound()); } MessageForCreationDto messageToReturn = _mapper.Map <MessageForCreationDto>(messageFromRepo); return(Ok(messageToReturn)); }
private async Task ValidateMessageForCreation(string userId, MessageForCreationDto messageForCreationDto) { if (userId != messageForCreationDto.UserId) { throw new InvalidUserIdException(typeof(Message)); } var conversationExisting = await _unitOfWork.ConversationRepository.IsConversationExistsById(messageForCreationDto.ConversationId); if (!conversationExisting) { throw new EntityNotFoundException(typeof(Conversation), messageForCreationDto.ConversationId); } await CheckUserConversationAccess(userId, messageForCreationDto.ConversationId); }
public async Task <Response> SendMessage(MessageForCreationDto message) { string messageAsJson = JsonSerializer.Serialize(message); var result = await _httpClient.PostAsync($"api/users/{message.SenderID}/messages", new StringContent(messageAsJson, Encoding.UTF8, "application/json")); if (result.IsSuccessStatusCode) { var response = new Response { Success = result.IsSuccessStatusCode, StatusCode = result.StatusCode.ToString(), ErrorMessage = result.Content.ReadAsStringAsync().Result }; return(response); } return(null); }
private async Task SendNotificationToUser(int userId, string emailContent) { var admins = await _userManager.GetUsersInRoleAsync(Constants.ADMIN); foreach (var admin in admins) { var messageForCreationDto = new MessageForCreationDto() { RecipientId = userId, SenderId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value), Content = emailContent }; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Message.AddMessage(message); } await _repo.Message.SaveAllAsync(); }
private async Task SendNotificationsForAdmins(int userId, string emailContent) { var admins = await _userManager.GetUsersInRoleAsync(Constants.ADMIN); foreach (var admin in admins) { var messageForCreationDto = new MessageForCreationDto() { RecipientId = admin.Id, SenderId = userId, Content = emailContent }; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Message.AddMessage(message); } await _repo.Message.SaveAllAsync(); }
public async Task <MessageDto> CreateMessage(string userId, MessageForCreationDto messageForCreationDto) { await ValidateMessageForCreation(userId, messageForCreationDto); var message = _mapper.Map <Message>(messageForCreationDto); _unitOfWork.MessageRepository.AddMessage(message); var conversation = await _unitOfWork.ConversationRepository.GetConversationById(message.ConversationId); UpdateConversationWithMessage(message, conversation); await _unitOfWork.Commit(); var messageDto = _mapper.Map <MessageDto>(message); return(messageDto); }
public async Task SendMessage(MessageForCreationDto messageDto, string connectionId) { if (messageDto.RecipientId != 0) { var recipient = await _repository.GetUser(messageDto.RecipientId); if (recipient != null) { var message = _mapper.Map <Message>(messageDto); _repository.Add(message); if (await _repository.SaveAll()) { await Clients.All.SendAsync("MessageReceived", messageDto); } } } }
[HttpPost] // not need messageId, system automatically generate messageId public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); // get sender's all info for instant message communication if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Set up userId messageForCreationDto.SenderId = userId; // Get recipient's info var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } // Want to map our messageForCreationDto into our message class var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); // var messageToReturn = _mapper.Map<MessageForCreationDto>(message); // MessageForCreationDto not include many properties like photUrl, knownAs etc. // It cannot return proper info to front end if (await _repo.SaveAll()) { // let me get the correct Id in return from the server when we create a new message // var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); // Use "message" as param, that would return passwordHash and passwordSalt. It's not suitable //return CreatedAtRoute("GetMessage", new {userId, id = message.Id}, message); } throw new Exception("Creating the message failed on save"); }
public async Task <Message> SaveMessage(int userId, MessageForCreationDto messageDto) { var recipient = await _usersService.GetUser(messageDto.RecipientId, false); if (recipient == null) { throw new BadRequestException($"Could not find user id '{messageDto.RecipientId}'."); } var message = _mapper.To <Message>(messageDto); message.SenderId = userId; _unitOfWork.Messages.Add(message); await _unitOfWork.CommitAsync(); return(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)); } }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { //pobranie z repozytorium id wysyłającego var sender = await _repo.GetUser(userId); //Sprawdzenie czy użytkownik istnieje if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //ustawienie SenderId w wiadomości na aktualnego użytkownika messageForCreationDto.SenderId = userId; //oraz odbiorcy wiadomości var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); //czy odbiorca istnieje if (recipient == null) { return(BadRequest("Could not find user")); } //zmapowanie DTO Wiadomości z klasą Wiadomości //przekształcenie messageForCreationDto => Message var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAllAsync()) { //przekształcenie Message => messageForCreationDto var messageToReturn = _mapper.Map <MessageToReturnDto>(message); //CreatedAtRoute(Name of root/nazwa ścieżki, objekt do przekazania) return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the messsafe failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); //checking if user is authorized if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //setting our messageForCreationDto senderId to UserId messageForCreationDto.SenderId = userId; //checking if the recipient Id exist in the db var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); //checking if the recipient id is null if (recipient == null) { return(BadRequest("Could not find user")); } //mapping our dto to our messages entity var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } else { throw new Exception("Creating the message failed on save"); } }
public async Task CreateMessage_InvalidRequest_ReturnsUnauthorizedResult() { var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "1"), })); var messageForCreation = new MessageForCreationDto() { SenderId = 1, RecipientId = 1 }; var mapperMock = new Mock <IMapper>(); var repositoryMock = new Mock <IRepositoryWrapper>(); repositoryMock.Setup(r => r.UserRepository.GetUserAsync(1)).ReturnsAsync(new User { Id = 1 }); repositoryMock.Setup(r => r.UserRepository.GetUserAsync(2)).ReturnsAsync(new User { Id = 2 }); repositoryMock.Setup(r => r.SaveAllAsync()).ReturnsAsync(true); repositoryMock.Setup(r => r.MessageRepository.Add(It.IsAny <Message>())); mapperMock.Setup(m => m.Map <Message>(It.IsAny <MessageForCreationDto>())).Returns(new Message()); mapperMock.Setup(m => m.Map <MessageToReturnDto>(It.IsAny <Message>())).Returns(new MessageToReturnDto()); var controllerMock = new MessagesController(repositoryMock.Object, mapperMock.Object); controllerMock.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = user } }; var result = await controllerMock.CreateMessage(2, messageForCreation); Assert.IsType <UnauthorizedResult>(result); }
private async Task SendNotificationsForEvaluator(int userId, string emailContent) { var evaluators = await _repo.User.LoadEvaluators(userId); foreach (var evaluator in evaluators) { // Only first rank of evaluators if (evaluator.Rank == 1) { var messageForCreationDto = new MessageForCreationDto() { RecipientId = evaluator.Id, SenderId = userId, Content = emailContent }; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Message.AddMessage(message); } } await _repo.Message.SaveAllAsync(); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { //get sender with userid var sender = await repo.GetUser(userId); //check if userId is equal to tokens nameid if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //set message's ender id to userid messageForCreationDto.SenderId = userId; //get recipientid var recipient = await repo.GetUser(messageForCreationDto.RecipientId); //if there is no recipient return nothing if (recipient == null) { return(BadRequest("მომხმარებელი ვერ ვიპოვეთ")); } //map from dto to class var message = mapper.Map <Message>(messageForCreationDto); //add message to db repo.Add(message); //try saving changes if (await repo.SaveAll()) { //map from class to dto var messageToReturn = mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } //throw exception if error throw new Exception("მესიჯი ვერ შეინახა და ვერ შეიქმნა"); }
public IActionResult UpdateMessage(int idUser, int idMessage, [FromBody] MessageForCreationDto message) { if (!_repository.UserExists(idUser)) { return(NotFound()); } var user = _repository.GetUser(idUser, false); if (!_repository.MessageExists(idUser, idMessage)) { return(NotFound()); } var currentMessage = _repository.GetMessage(idUser, idMessage); currentMessage.Content = message.Content; currentMessage.MessageDateCreate = message.MessageDateCreate; _repository.Save(); return(NoContent()); }