public async Task <GetCreateMessageChatView> CreateMessage(string messageText, Guid roomId, string userId) { User user = await _userManager.FindByIdAsync(userId); if (user == null) { throw new Exception("User is not find"); } Message message = new Message { Text = messageText, UserId = userId }; MessageInRoom messageInRoom = new MessageInRoom { RoomId = roomId, MessageId = message.Id }; GetCreateMessageChatView response = new GetCreateMessageChatView() { Id = message.Id, CreationAt = _dateTimeHelper.FormatDateFromDb(message.CreationAt), Text = message.Text, FullName = $"{user.FirstName} {user.LastName}", UserId = userId }; await _messageRepository.Create(message); await _messageInRoomRepository.Create(messageInRoom); return(response); }
public async Task <GetAllRoomsChatView> GetAllRooms() { GetAllRoomsChatView response = new GetAllRoomsChatView(); List <MessageInRoom> lastMessages = new List <MessageInRoom>(); List <Room> rooms = await _roomRepository.GetAll(); List <MessageInRoom> messageInRooms = await _messageInRoomRepository.GetAllRoomsAndMessages(); if (!messageInRooms.Any()) { throw new Exception("Message in rooms is not found"); } if (!rooms.Any()) { throw new Exception("Rooms is not found"); } messageInRooms .GroupBy(x => x.RoomId) .ToList() .ForEach(item => { MessageInRoom lastMessage = item .Where(x => x.RoomId == item.Key) .OrderByDescending(x => x.CreationAt) .FirstOrDefault(); lastMessages.Add(lastMessage); }); if (!messageInRooms.Any()) { return(response); } response.Rooms = _mapper.Map(lastMessages, response.Rooms); if (rooms.Count > response.Rooms.Count) { List <Guid> roomsWithMessagesIds = response.Rooms .Select(x => x.Id) .ToList(); var roomsWithotMessages = rooms .Where(x => !roomsWithMessagesIds .Contains(x.Id)) .ToList() .Select(x => new RoomGetAllRoomsChatViewtem() { Id = x.Id, Name = x.Name, Photo = x.Photo, LastMessage = "No messages yet" }) .ToList(); response.Rooms.AddRange(roomsWithotMessages); } return(response); }