예제 #1
0
        public async Task <bool> CheckStatusAsync(AddMessageDto request)
        {
            var chat = await this._unit.ChatRepository.GetAsync(request.chatId);

            if (chat == null)
            {
                throw new ChatNotExistException("Given chat not exist!!", 400);
            }

            var currentUser = await this._auth.FindByIdUserAsync(request.userId);

            if (currentUser == null)
            {
                throw new UserNotExistException("Given user not exist!!", 400);
            }

            var requestedUserId = chat.FirstUserId == currentUser.Id ? chat.SecondUserId : chat.FirstUserId;

            if ((await _unit.BlockedUserRepository.IsBlockedUserAsync(requestedUserId, currentUser.Id)) == null)
            {
                return(false);
            }

            return(true);
        }
예제 #2
0
        public async Task <GetMessageDto> SendMessage(AddMessageDto messageDto)
        {
            var chat = await _unitOfWork.Repository <Chat>().GetAsync(c => c.Id == messageDto.ChatId);

            if (chat == null)
            {
                return(null);
            }

            var creator = await _authentication.GetCurrentUserAsync();

            messageDto.CreatedById    = creator.Id;
            messageDto.CreatedDateUtc = DateTime.Now;
            var message = _mapper.Map <Message>(messageDto);
            await _unitOfWork.Repository <Message>().AddAsync(message);

            await _unitOfWork.SaveChangesAsync();

            var getMessage = _mapper.Map <GetMessageDto>(message);

            getMessage.FirstName = creator.FirstName;
            getMessage.LastName  = creator.LastName;
            getMessage.ImagePath = creator.ImagePath;
            return(getMessage);
        }
        public async Task <GetMessageDto> PostMessage(string id, AddMessageDto messageDto)
        {
            var response = await client.PostAsync($"api/conversation/{id}",
                                                  new StringContent(JsonConvert.SerializeObject(messageDto),
                                                                    Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode)
            {
                throw new ChatServiceException($"Failed to add message {messageDto.Text}", response.ReasonPhrase, response.StatusCode);
            }

            try
            {
                var content = await response.Content.ReadAsStringAsync();

                var message = JsonConvert.DeserializeObject <GetMessageDto>(content);
                return(message);
            }
            catch (JsonException e)
            {
                throw new ChatServiceException($"Failed to deserialize message for conversation {id}", e,
                                               "Serialization Exception", HttpStatusCode.InternalServerError);
            }
            catch (Exception e)
            {
                if (e is ChatServiceException)
                {
                    throw;
                }

                throw new ChatServiceException("Failed to reach chat service", e,
                                               "Internal Server Error", HttpStatusCode.InternalServerError);
            }
        }
        public async Task AddMessageReturns500IfNotificationServiceDown()
        {
            mockService.Setup(service => service.SendNotification(It.IsAny <NotificationDto>()))
            .ThrowsAsync(new ChatServiceException("test", "test", new HttpStatusCode()));
            AddMessageDto messageDto = new AddMessageDto("Hi!", "amansour");

            TestUtils.AssertStatusCode(HttpStatusCode.InternalServerError, await myController.Post("amansour_nbilal", messageDto));
        }
        public async Task AddMessageReturns500IfUnknownException()
        {
            mockStore.Setup(store => store.AddMessage(It.IsAny <string>(), It.IsAny <Message>()))
            .ThrowsAsync(new Exception("Unknown Exception!"));
            AddMessageDto messageDto = new AddMessageDto("Hi!", "amansour");

            TestUtils.AssertStatusCode(HttpStatusCode.InternalServerError, await myController.Post("amansour_nbilal", messageDto));
        }
        public async Task AddMessageReturns503IfStorageUnavailable()
        {
            mockStore.Setup(store => store.AddMessage(It.IsAny <string>(), It.IsAny <Message>()))
            .ThrowsAsync(new StorageUnavailableException("Storage is unavailable!"));
            var messageDto = new AddMessageDto("Hi!", "amansour");

            TestUtils.AssertStatusCode(HttpStatusCode.ServiceUnavailable, await myController.Post("amansour_nbilal", messageDto));
        }
예제 #7
0
        public async Task <MessageDto> AddMessage(AddMessageDto message)
        {
            var messageToAdd = _mapper.Map <Message>(message);

            _context.Messages.Add(messageToAdd);
            await _context.SaveChangesAsync();

            var result = _mapper.Map <MessageDto>(messageToAdd);

            return(result);
        }
예제 #8
0
        public async Task <ActionResult> AddMessage(int claimId, AddMessageDto addMessageDto)
        {
            if (addMessageDto == null)
            {
                throw new ArgumentNullException(nameof(addMessageDto));
            }

            await claimManager.AddMessage(claimId, addMessageDto.AuthorUsername, addMessageDto.Message).ConfigureAwait(false);

            return(Ok());
        }
예제 #9
0
 public async Task AddMessage([FromBody] AddMessageDto addMessageDto)
 {
     try
     {
         await _messageService.AddMessage(addMessageDto);
     }
     catch (Exception e)
     {
         throw new ApplicationException(e.Message);
     }
 }
        public void Initialize()
        {
            client = TestUtils.CreateTestServerAndClient();

            conversationDto1 = new AddConversationDto
            {
                Participants = new List <string> {
                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                }
            };
            conversationDto2 = new AddConversationDto
            {
                Participants = new List <string> {
                    conversationDto1.Participants[0], Guid.NewGuid().ToString()
                }
            };
            conversationDto3 = new AddConversationDto
            {
                Participants = new List <string> {
                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                }
            };
            conversationDto4 = new AddConversationDto
            {
                Participants = new List <string> {
                    conversationDto1.Participants[0], Guid.NewGuid().ToString()
                }
            };

            userProfile1 = new CreateProfileDto
            {
                Username  = conversationDto1.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };
            userProfile2 = new CreateProfileDto
            {
                Username  = conversationDto2.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };
            userProfile3 = new CreateProfileDto
            {
                Username  = conversationDto4.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };

            messageDto1 = new AddMessageDto("Hi!", conversationDto1.Participants[0]);
            messageDto2 = new AddMessageDto("Hello!", conversationDto1.Participants[1]);
            messageDto3 = new AddMessageDto("Hi!", "foo");
            messageDto4 = new AddMessageDto("Kifak!", conversationDto1.Participants[1]);
        }
        public async Task <IActionResult> Post(string conversationId, [FromBody] AddMessageDto dto)
        {
            using (logger.BeginScope("This log is for {conversationId}", conversationId))
            {
                var stopWatch = Stopwatch.StartNew();
                try
                {
                    var message = await store.AddMessage(conversationId, new Message(dto));
                    await CreateMessagePayloadAndSend(conversationId, message);

                    logger.LogInformation(Events.MessageAdded, "Message Added Successfully", DateTime.UtcNow);
                    var messageDto = new GetMessageDto(message);
                    return(Ok(messageDto));
                }
                catch (StorageUnavailableException e)
                {
                    logger.LogError(Events.StorageError, e, $"Storage was not available to add message",
                                    DateTime.UtcNow);
                    return(StatusCode(503, "Failed to reach Storage"));
                }
                catch (ConversationNotFoundException e)
                {
                    logger.LogError(Events.ConversationNotFound, e,
                                    $"Conversation of Id = {conversationId} was not found", DateTime.UtcNow);
                    return(NotFound($"Conversation of Id = {conversationId} was not found"));
                }
                catch (InvalidDataException e)
                {
                    logger.LogError(Events.UsernameNotFound, e, $"Username is not in participants", DateTime.UtcNow);
                    return(StatusCode(400, "Sender Username doesn't exist in conversation"));
                }
                catch (Exception e)
                {
                    logger.LogError(Events.InternalError, e, $"Failed to send messages for {conversationId}",
                                    DateTime.UtcNow);
                    return(StatusCode(500, $"Failed to send message"));
                }
                finally
                {
                    PostMessageMetric.TrackValue((double)stopWatch.ElapsedMilliseconds);
                }
            }
        }
        public async Task AddMessage(AddMessageDto addMessageDto)
        {
            await _messageRepository.CreateAsync(new Message
            {
                CourseId = addMessageDto.CourseId,
                Date     = addMessageDto.Date,
                Text     = addMessageDto.Text,
                UserId   = addMessageDto.UserId
            });

            await _chartHub.Clients.All.SendAsync("getNewMessage", new MessageDto
            {
                Login    = (await _userRepository.GetByAsync(u => u.Id == addMessageDto.UserId)).Login,
                CourseId = addMessageDto.CourseId,
                Date     = addMessageDto.Date,
                Text     = addMessageDto.Text,
                UserId   = addMessageDto.UserId
            });
        }
예제 #13
0
        public async Task SendToAll(AddMessageDto message)
        {
            message.userId = Convert.ToInt32(Context.User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var isblocked = _cache.Get($"{message.userId}:{message.chatId}");

            if (isblocked == null)
            {
                isblocked = await this._userService.CheckStatusAsync(message);

                _cache.Set($"{message.userId}:{message.chatId}", isblocked, new MemoryCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                });
            }

            if (!(bool)isblocked)
            {
                var newmessage = await _messageService.AddMessageAsync(message);

                await Clients.Group(message.chatId.ToString()).SendAsync("update", newmessage, message.chatId);
            }
        }
예제 #14
0
        public async Task <GetMessageDto> AddMessageAsync(AddMessageDto message)
        {
            var user = await _auth.FindByIdUserAsync(message.userId);

            if (user == null)
            {
                throw new UserNotExistException("Given user not exist!!", 400);
            }

            var chat = await _unit.ChatRepository.GetAsync(message.chatId);

            if (chat == null)
            {
                throw new ChatNotExistException("Given chatid is incorrect!!", 400);
            }

            if (!string.IsNullOrEmpty(message.Content))
            {
                var newmessage = new Message()
                {
                    Content     = message.Content,
                    TimeCreated = DateTime.Now,
                    UserId      = user.Id,
                    ChatId      = message.chatId
                };

                await this._unit.MessageRepository.CreateAsync(newmessage);

                chat.LastMessage = newmessage;

                await _unit.Commit();

                return(_map.Map <GetMessageDto>(newmessage));
            }

            throw new MessageInCorrectException("Given message is incorrect!!", 400);
        }
예제 #15
0
        public async Task SendMessage(AddMessageDto message)
        {
            var addedMessage = await _messageService.AddMessage(message);

            await Clients.All.MessageAdded(addedMessage);
        }