public async Task <ActionResult <IEnumerable <ChatDto> > > List()
        {
            IEnumerable <Chat> chats = await this._chatRepository.GetChatsAsync(User.GetUserId());

            var chatsDto = _mapper.Map <IEnumerable <ChatDto> >(chats);

            foreach (var chatDto in chatsDto)
            {
                chatDto.UnreadMessages = await _messagesService.CountUnreadMessages(User.GetUserId(), chatDto.Id);
            }
            return(Ok(chatsDto));
        }
Exemplo n.º 2
0
        public async Task Invite(string userLogin, int chatId)
        {
            //ToDo: Move this code to service
            Chat chat = await _chatRepository.GetById(chatId);

            AppUser user = await _userRepository.GetUserByLoginAsync(userLogin);

            int adminId = Context.User.GetUserId();

            if (user == null)
            {
                throw new Exception($"User with id {user.Id} was not found");
            }
            if (chat == null)
            {
                throw new Exception($"Chat with id {chatId} was not found");
            }
            if (chat.OwnerId == user.Id)
            {
                throw new Exception($"User with id {user.Id} is the admin of chat with id {chatId}");
            }
            if (chat.OwnerId != adminId)
            {
                throw new Exception($"You do not have administrator privileges to add members to the chat");
            }

            UserChats userChat = await _context.UserChats.FirstOrDefaultAsync(x => x.ChatId == chatId && x.UserId == user.Id);

            if (userChat != null)
            {
                throw new Exception($"User with id {user.Id} is already in the chat with id {chatId}");
            }

            _context.UserChats.Add(new UserChats {
                ChatId = chatId, UserId = user.Id
            });
            await _context.SaveChangesAsync();

            ChatDto chatDto = _mapper.Map <ChatDto>(await _chatRepository.GetById(chatId));

            chatDto.UnreadMessages = await _messagesService.CountUnreadMessages(user.Id, chatId);

            await Clients.User(user.Id.ToString()).SendAsync("joinedToNewChat", chatDto);
        }