public async Task <ActionResult> Leave([FromQuery] int chatId)
        {
            Chat chat = await _chatRepository.GetById(chatId);

            if (chat == null)
            {
                return(BadRequest($"Chat with id {chatId} was not found"));
            }

            int userId = User.GetUserId();

            if (chat.OwnerId == User.GetUserId())
            {
                if (chat.Members.Any())
                {
                    return(BadRequest($"You cannot leave your own chat until there are other chat members"));
                }
                chat.IsActive = false;
            }
            else
            {
                UserChats userChat = await _context.UserChats.FirstOrDefaultAsync(x => x.ChatId == chatId && x.UserId == User.GetUserId());

                if (userChat == null)
                {
                    return(BadRequest($"User with id {User.GetUserId()} does not belong to chat with id {chatId}"));
                }
                _context.UserChats.Remove(userChat);
            }

            await _context.SaveChangesAsync();

            return(Ok());
        }
Esempio n. 2
0
 public void CallBackChatAdded(ChatDTO chat)
 {
     App.Current.Dispatcher.BeginInvoke((Action) delegate()
     {
         Thread.Sleep(20);
         UserChats.Add(InitializeChat(chat));
     });
 }
Esempio n. 3
0
        public async Task <UserChats> Create(UserChats obj)
        {
            _unitOfWork.IUserChatRepository.Add(obj);

            await _unitOfWork.CommitAsync();

            return(obj);
        }
Esempio n. 4
0
 public void PopulateUserChats(List <Chat> chats)
 {
     foreach (Chat chat in chats)
     {
         lock (UserChatsLock)
         {
             UserChats.Add(chat);
         }
     }
 }
Esempio n. 5
0
        public IActionResult GetPrivateChat(int userId2, int workspaceId)
        {
            if (_unitOfWork.Users.GetByID(userId2) == null)
            {
                return(BadRequest("The user does not exist"));
            }

            if (_unitOfWork.Workspaces.GetByID(workspaceId) == null)
            {
                return(BadRequest("The workspace does not exist"));
            }

            User user1 = this.GetAuthenticatedUser();

            var commonChatIds = _unitOfWork.UserChats.GetCommonChats(user1.Id, userId2);

            Chat privateCommonChat;

            foreach (var commonChatId in commonChatIds)
            {
                privateCommonChat = _unitOfWork.Chats.GetChatIfPrivate(commonChatId, workspaceId);

                if (privateCommonChat != null)
                {
                    return(Ok(privateCommonChat));
                }
            }

            UserChats userChat1 = new UserChats {
                UserId = user1.Id
            };
            UserChats userChat2 = new UserChats {
                UserId = userId2
            };

            privateCommonChat = new Chat
            {
                CreatorID   = user1.Id,
                DateCreated = DateTime.Now,
                IsPrivate   = true,
                Name        = "dm" + user1.Id + "," + userId2,
                WorkspaceId = workspaceId,
                UserChats   = new List <UserChats> {
                    userChat1, userChat2
                }
            };

            _unitOfWork.Chats.Insert(privateCommonChat);
            _unitOfWork.Save();

            return(Created("No Url at the moment", privateCommonChat));
        }
Esempio n. 6
0
 public void CallBackMsg(MessageDTO msg)
 {
     App.Current.Dispatcher.BeginInvoke((Action) delegate()
     {
         Thread.Sleep(20);
         ChatModel currentChat = UserChats.FirstOrDefault((chat) => chat.Chat.ChatId == msg.ChatId);
         currentChat.Messages.Add(
             new MessageModel()
         {
             Message  = msg
             , Sender = currentChat.Members.FirstOrDefault((user)
                                                           => user.User.User.UserId == msg.SenderId).User
         });
     });
 }
Esempio n. 7
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);
        }
Esempio n. 8
0
        public IActionResult AddUserToChannel(int channelId, [FromBody] string UserName)
        {
            UserChats userChat = new UserChats();
            User      user     = _unitOfWork.Users.GetUserByUserName(UserName);
            Chat      chat     = _unitOfWork.Chats.GetByID(channelId);

            if (user != null && chat != null)
            {
                userChat.ChatId = channelId;
                userChat.UserId = user.Id;
                _unitOfWork.UserChats.Insert(userChat);
                _unitOfWork.Save();
                //send message to channel ----- call taher's function
                return(Ok(userChat));
            }
            else
            {
                return(BadRequest());
            }
        }
Esempio n. 9
0
        public IActionResult ToggleMuteChat([FromBody] ChatIdDTO chat)
        {
            User user = this.GetAuthenticatedUser();

            IQueryable <int> userChatsIds = _unitOfWork.Users.GetChatsIdsByUserId(user.Id);

            UserChats userChat = userChatsIds.Any(uci => uci == chat.ChatID) ? _unitOfWork.UserChats.GetUserChatByIds(user.Id, chat.ChatID) : null;

            if (userChat == null)
            {
                return(BadRequest("This chat either does not exist or the user is not allowed to edit this chat"));
            }

            userChat.IsMuted = !userChat.IsMuted;

            _unitOfWork.Users.Update(user);
            _unitOfWork.Save();

            return(Ok(new { isMuted = userChat.IsMuted }));
        }
Esempio n. 10
0
        public void AddMessage(Message message, string receiverUsername)
        {
            string senderUsername = message.SenderUsername;

            bool found = false;

            foreach (Chat chat in UserChats)
            {
                if (ValidChat(chat, senderUsername, receiverUsername))
                {
                    chat.Messages.Add(message);
                    found = true;
                }
            }

            if (!found)
            {
                Chat newChat = new Chat(receiverUsername, senderUsername, new List <Message>());

                newChat.Messages.Add(message);

                lock (UserChatsLock)
                {
                    UserChats.Add(newChat);
                }
            }

            if (_SelectedChat != null)
            {
                if (_SelectedChat.RecipientUsername == receiverUsername || CUsername == receiverUsername)
                {
                    Application.Current.Dispatcher.Invoke(delegate
                    {
                        ChatMessages.Add(senderUsername + ": " + message.Content);
                    });

                    OnPropertyChanged("SelectedChat");
                }
            }
        }
Esempio n. 11
0
        protected override async Task OnInitializedAsync()
        {
            var claimsPrincipal = await AuthenticationStateProvider.GetAuthenticationStateAsync();

            var user = await UserManager.GetUserAsync(claimsPrincipal.User);

            if (user is null)
            {
                var userName = UserManager.GetUserName(claimsPrincipal.User);

                if (userName is null)
                {
                    return;
                }

                user = await UserManager.Users.FirstOrDefaultAsync(x => x.UserName == userName);
            }

            _currentChatUser = DbContext.ChatUsers.Include(x => x.UserNameColor).FirstOrDefault(x => x.AppUser == user);
            //.Include(x => x.AppUser)
            //.Include(x => x.UserNameColor)
            //.FirstOrDefaultAsync(x => x.AppUser == user);

            // todo: rewrite query
            var query = DbContext.ChatRooms
                        .Include(x => x.ChatMessages)
                        .Include(x => x.ChatUsers).ThenInclude(x => x.UserNameColor)
                        .Include(x => x.ChatUsers).ThenInclude(x => x.AppUser);


            foreach (var chatRoom in query)
            {
                if (chatRoom.ChatUsers.Contains(_currentChatUser))
                {
                    UserChats.Add(chatRoom);
                }
            }

            await base.OnInitializedAsync();
        }
        public async Task <ActionResult> Invite([FromQuery] string userLogin, [FromQuery] int chatId)
        {
            Chat chat = await _chatRepository.GetById(chatId);

            AppUser user = await _userRepository.GetUserByLoginAsync(userLogin);

            if (user == null)
            {
                return(NotFound($"User with login {userLogin} was not found"));
            }
            if (chat == null)
            {
                return(NotFound($"Chat with id {chatId} was not found"));
            }
            if (chat.OwnerId == user.Id)
            {
                return(BadRequest($"User with id {user.Id} is the admin of chat with id {chatId}"));
            }
            if (chat.OwnerId != User.GetUserId())
            {
                return(BadRequest($"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)
            {
                return(BadRequest($"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();

            return(Ok());
        }
Esempio n. 13
0
        public ApplicationContext()
        {
            Database.EnsureDeleted();
            Database.EnsureCreated();

            UserData user = new UserData();

            user.Login    = "******";
            user.Password = "******";

            Users.Add(user);
            UserData user1 = new UserData();

            user1.Login    = "******";
            user1.Password = "******";
            Users.Add(user1);

            UserData user2 = new UserData();

            user2.Login    = "******";
            user2.Password = "******";
            Users.Add(user2);
            SaveChanges();

            Token token = new Token();

            token.UserId  = user.Id;
            token.TokenId = "dferw";
            Tokens.Add(token);

            Token token1 = new Token();

            token1.UserId  = user1.Id;
            token1.TokenId = "2w3e4r";
            Tokens.Add(token1);

            Token token2 = new Token();

            token2.UserId  = user2.Id;
            token2.TokenId = "98765";
            Tokens.Add(token2);
            SaveChanges();

            Chat chat = new Chat();

            chat.Name   = "Geography";
            chat.UserId = user.Id;

            Chats.Add(chat);
            SaveChanges();

            UserChat userChat = new UserChat();

            userChat.ChatId = chat.Id;
            userChat.UserId = user.Id;
            UserChats.Add(userChat);
            SaveChanges();

            UserChat userChat1 = new UserChat();

            userChat1.ChatId = chat.Id;
            userChat1.UserId = user1.Id;
            UserChats.Add(userChat1);
            SaveChanges();

            UserChat userChat2 = new UserChat();

            userChat2.ChatId = chat.Id;
            userChat2.UserId = user2.Id;
            UserChats.Add(userChat2);
            SaveChanges();
        }
Esempio n. 14
0
        public async Task <UserChats> Update(UserChats objToBeUpdated, UserChats obj)
        {
            await _unitOfWork.CommitAsync();

            return(obj);
        }
Esempio n. 15
0
        public async Task Remove(UserChats obj)
        {
            _unitOfWork.IUserChatRepository.Remove(obj);

            await _unitOfWork.CommitAsync();
        }
Esempio n. 16
0
        public async Task <IActionResult> create([FromBody] ChatModel mappingResource)
        {
            ReturnResult returnResult = new ReturnResult();

            if (mappingResource == null)
            {
                returnResult.code    = 1;
                returnResult.message = "no data posted";
                return(Ok(returnResult));
            }

            if (string.IsNullOrEmpty(mappingResource.Message))
            {
                returnResult.code    = 1;
                returnResult.message = "message reqired";
                return(Ok(returnResult));
            }

            if (mappingResource.RecieverId == Guid.Empty)
            {
                returnResult.code    = 1;
                returnResult.message = "receiver reqired";
                return(Ok(returnResult));
            }

            try
            {
                Users Sender = await iUserService.GetByEmail(User.Identity.Name);

                Users Reciever = await iUserService.GetById(mappingResource.RecieverId);

                UserChats userChatObj = new UserChats();
                userChatObj.Id          = Guid.NewGuid();
                userChatObj.Message     = mappingResource.Message;
                userChatObj.SenderId    = Sender.Id;
                userChatObj.RecieverId  = Reciever.Id;
                userChatObj.ReadStatus  = false;
                userChatObj.MessageTime = DateTime.Now;

                UserChats returnObj = await iUserChatService.Create(userChatObj);

                if (returnObj == null)
                {
                    returnResult.code    = 2;
                    returnResult.message = "text_chat_err";
                }
                else
                {
                    returnResult.code    = 1;
                    returnResult.message = "text_chat_create_success";
                    //await _hubContext.Clients.All.SendAsync("ReceiveMessage", userChatObj.Id, userChatObj.SenderId, userChatObj.RecieverId, Sender.FirstName + " " + Sender.LastName, returnObj.MessageTime.ToLongTimeString(), mappingResource.Message);
                    await _hubContext.Clients.Groups(Reciever.Id.ToString(), Sender.Id.ToString()).SendAsync("ReceiveMessage", userChatObj.Id, userChatObj.SenderId, userChatObj.RecieverId, Sender.FirstName + " " + Sender.LastName, returnObj.MessageTime.ToLongTimeString(), mappingResource.Message);
                }

                return(Ok(returnResult));
            }
            catch (Exception ex)
            {
                returnResult.code    = 0;
                returnResult.data    = null;
                returnResult.message = ex.Message;
                return(Ok(returnResult));
            }
        }