Пример #1
0
        public bool InitiateChat(string clientToUserId)
        {
            // Get current user
            var fromUser = Helper.CurrentUser;

            if (fromUser == null)
            {
                return(false);
            }

            // Check to user is Authenticate User, can't chat to guest user
            var toUserId = EncryptUtils.Decrypt(clientToUserId);
            int lToUserId;

            int.TryParse(toUserId, out lToUserId);
            if (lToUserId <= 0)
            {
                return(false);
            }
            // Get from User Online list
            bool isToUserOnline;
            User toUserOnline = null;

            if (_UserOnlines.ContainsKey(lToUserId))
            {
                toUserOnline   = _UserOnlines[lToUserId];
                isToUserOnline = true;
            }
            else
            {
                isToUserOnline = false;
                // Get user from User table
                toUserOnline = UserBO.GetById(lToUserId);
            }

            // Exist online chat room
            var id1 = fromUser.Id;
            var id2 = lToUserId;

            Helper.Sort(ref id1, ref id2);
            var chatRoomExisted = ChatRoomBO.CheckExisted(id1, id2);
            var serverChatRoom  = chatRoomExisted == null ? null : chatRoomExisted.ToServerChatRoom();
            // total unread message
            var totalUnreadMsg = 0;

            if (serverChatRoom == null)
            {
                var chatRoom = new ChatRoom
                {
                    FromUserId = id1,
                    ToUserId   = id2,
                    CreateDate = DateTime.Now
                };
                var chatRoomId = ChatRoomBO.Insert(chatRoom);
                if (chatRoomId <= 0)
                {
                    return(false);
                }

                serverChatRoom = chatRoom.ToServerChatRoom();
                // Add to user to server chat rooms
                serverChatRoom.ChatUsers.Add(fromUser);
                serverChatRoom.ChatUsers.Add(toUserOnline);
                totalUnreadMsg = ChatMessageBO.CountUnread(serverChatRoom.Id, fromUser.Id);
                var clientChatRoom = serverChatRoom.ToClientChatRoom();
                chatClient.initiateChatUI(fromUser.Id.ToString(), clientChatRoom, isToUserOnline, totalUnreadMsg);
            }
            else
            {
                serverChatRoom.ChatUsers = new List <User>
                {
                    UserBO.GetById(serverChatRoom.FromUserId),
                    UserBO.GetById(serverChatRoom.ToUserId),
                };
                totalUnreadMsg = ChatMessageBO.CountUnread(serverChatRoom.Id, fromUser.Id);
                chatClient.initiateChatUI(fromUser.Id.ToString(), serverChatRoom.ToClientChatRoom(), isToUserOnline, totalUnreadMsg);
            }

            _OnlineChatRooms.TryAdd(serverChatRoom.Id, serverChatRoom);
            return(true);
        }