Esempio n. 1
0
        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");
        }