public ResponseModel GetChatSession()
        {
            ResponseModel    objResponseModel = new ResponseModel();
            int              statusCode       = 0;
            string           statusMessage    = "";
            ChatSessionModel ChatSession      = new ChatSessionModel();

            try
            {
                //string token = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                //Authenticate authenticate = new Authenticate();
                //authenticate = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(token));


                CustomerChatCaller customerChatCaller = new CustomerChatCaller();

                ChatSession = customerChatCaller.GetChatSession(new CustomerChatService(_connectionString));

                statusCode    = ChatSession != null ? (int)EnumMaster.StatusCode.Success : (int)EnumMaster.StatusCode.RecordNotFound;
                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);


                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = ChatSession;
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// get customer chat session
        /// </summary>
        /// <returns></returns>
        public ChatSessionModel GetChatSession()
        {
            MySqlCommand     cmd         = new MySqlCommand();
            DataSet          ds          = new DataSet();
            ChatSessionModel ChatSession = new ChatSessionModel();

            try
            {
                if (conn != null && conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                cmd            = new MySqlCommand("SP_GetChatSession", conn);
                cmd.Connection = conn;

                cmd.CommandType = CommandType.StoredProcedure;

                MySqlDataAdapter da = new MySqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);

                if (ds != null && ds.Tables != null)
                {
                    if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        ChatSession.ProgramCode         = ds.Tables[0].Rows[0]["ProgramCode"] == DBNull.Value ? string.Empty : Convert.ToString(ds.Tables[0].Rows[0]["ProgramCode"]);
                        ChatSession.TenantID            = ds.Tables[0].Rows[0]["TenantID"] == DBNull.Value ? 0 : Convert.ToInt32(ds.Tables[0].Rows[0]["TenantID"]);
                        ChatSession.ChatSessionValue    = ds.Tables[0].Rows[0]["ChatSessionValue"] == DBNull.Value ? 0 : Convert.ToInt32(ds.Tables[0].Rows[0]["ChatSessionValue"]);
                        ChatSession.ChatSessionDuration = ds.Tables[0].Rows[0]["ChatSessionDuration"] == DBNull.Value ? string.Empty : Convert.ToString(ds.Tables[0].Rows[0]["ChatSessionDuration"]);
                        ChatSession.ChatDisplayValue    = ds.Tables[0].Rows[0]["ChatDisplayValue"] == DBNull.Value ? 0 : Convert.ToInt32(ds.Tables[0].Rows[0]["ChatDisplayValue"]);
                        ChatSession.ChatDisplayDuration = ds.Tables[0].Rows[0]["ChatDisplayDuration"] == DBNull.Value ? string.Empty : Convert.ToString(ds.Tables[0].Rows[0]["ChatDisplayDuration"]);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                if (ds != null)
                {
                    ds.Dispose();
                }
            }

            return(ChatSession);
        }
Ejemplo n.º 3
0
        public async Task SendChatMessage(SendMessageModel model)
        {
            // Centralized timestamp
            model.Message.TimeStamp   = DateTime.UtcNow.Ticks;
            model.Message.CreatedDate = DateTime.UtcNow;

            // We will add new chat session when reaching Threshold or next day
            if (_chatContext.WantToAddNewSession(model.ChatSessionId))
            {
                var currentChatSession = _chatContext.GetChatSession(model.ChatSessionId);
                var newChatSession     = new ChatSessionModel
                {
                    ChatRoomId        = currentChatSession.ChatRoomId,
                    CreatedDate       = DateTime.UtcNow,
                    Messages          = new Queue <MessageModel>(),
                    PreviousSessionId = currentChatSession.SessionId,
                    SessionId         = DataUtil.GenerateUniqueId(),
                    LastMessageDate   = DateTime.UtcNow
                };

                currentChatSession.NextSessionId   = newChatSession.SessionId;
                currentChatSession.LeaveDate       = DateTime.UtcNow;
                currentChatSession.LastMessageDate = DateTime.UtcNow;
                // Save the current one to DB
                await _chatSessionRepository.UpsertAsync(currentChatSession.ToSession(true));

                currentChatSession.IsInDb = true;

                _chatContext.AddChatRoomSession(newChatSession);

                await Clients.Caller.AddNewChatSession(newChatSession);

                _chatContext.SendMessage(newChatSession.SessionId, model.Message);

                await Clients.User(model.Receiver).AddNewChatSession(newChatSession);

                await Clients.User(Context.UserIdentifier).BoardcastSentMessage(newChatSession.ChatRoomId, newChatSession.SessionId, model.LastSentHashCode, model.Message);

                await Clients.User(model.Receiver).ReceivedMessage(currentChatSession.ChatRoomId, newChatSession.SessionId, model.Message);
            }
            else
            {
                _chatContext.SendMessage(model.ChatSessionId, model.Message);

                await Clients.User(Context.UserIdentifier).BoardcastSentMessage(model.ChatRoomId, model.ChatSessionId, model.LastSentHashCode, model.Message);

                await Clients.User(model.Receiver)
                .ReceivedMessage(model.ChatRoomId, model.ChatSessionId, model.Message);
            }
        }
Ejemplo n.º 4
0
        public void AddChatRoomSession(ChatSessionModel chatSession)
        {
            var numberOfSessions = chatSessions.Count(a => a.ChatRoomId == chatSession.ChatRoomId);

            if (numberOfSessions < _options.CurrentValue.MaximumSessionsPerChatRoom)
            {
                chatSessions.Add(chatSession);
            }
            else
            {
                // Remove last created
                var lastSession      = chatSessions.Where(a => a.ChatRoomId == chatSession.ChatRoomId).OrderBy(a => a.LastMessageDate).First();
                var lastSessionIndex = chatSessions.IndexOf(lastSession);
                chatSessions.RemoveAt(lastSessionIndex);
                chatSessions.Add(chatSession);
            }
        }
Ejemplo n.º 5
0
        public async Task LoadPrevious(string previousSessionId)
        {
            // Check if it stayed on ChatContext
            var foundSession = _chatContext.GetChatSession(previousSessionId);

            if (foundSession != null)
            {
                await Clients.Caller.AddPreviousSession(foundSession);
            }
            else
            {
                // Find in Db
                var entityChatSession = await _chatSessionRepository.GetOneAsync(previousSessionId);

                var preChatSessionModel = new ChatSessionModel
                {
                    ChatRoomId        = entityChatSession.ChatRoomId,
                    CreatedDate       = entityChatSession.CreatedDate,
                    NextSessionId     = entityChatSession.NextSessionId,
                    PreviousSessionId = entityChatSession.PreviousSessionId,
                    Messages          = new Queue <MessageModel>(),
                    SessionId         = entityChatSession.Id,
                    IsInDb            = true
                };

                if (entityChatSession.Conversations != null)
                {
                    foreach (var message in entityChatSession.Conversations.OrderBy(a => a.Timestamp))
                    {
                        preChatSessionModel.Messages.Enqueue(new MessageModel
                        {
                            Id               = message.Id,
                            Message          = message.Message,
                            FormattedMessage = message.MessageTransform,
                            TimeStamp        = message.Timestamp,
                            UserName         = message.Username,
                            CreatedDate      = message.CreatedDate,
                            AttachmentFiles  = new List <AttachmentFile>()
                        });
                    }
                }

                _chatContext.AddChatRoomSession(preChatSessionModel);
                await Clients.Caller.AddPreviousSession(preChatSessionModel);
            }
        }
Ejemplo n.º 6
0
        public async Task OpenDoubleChatRoom(Models.OnlineUser invitee)
        {
            // Check this room is existed or not
            var              invitor              = _chatContext.GetOnlineUser(Context.UserIdentifier);
            var              founDoubleRoom       = _chatContext.GetDoubleRoom(invitor, invitee);
            string           chatRoomId           = string.Empty;
            string           chatSessionId        = string.Empty;
            bool             isExistedOnDb        = false;
            bool             createNewSession     = false;
            ChatSessionModel chatSessionModel     = null;
            ChatSessionModel previousSessionModel = null;
            ChatRoomModel    chatRoomModel        = null;

            if (founDoubleRoom == null)
            {
                // Try to fetch from database
                var foundRoomInDb = (await _chatRoomRepository
                                     .GetAllAsync(a => a.Type == RoomType.Double &&
                                                  a.Participants.Any(b => b.Username == Context.UserIdentifier) &&
                                                  a.Participants.Any(c => c.Username == invitee.UserName))).FirstOrDefault();
                if (foundRoomInDb != null)
                {
                    chatRoomModel = new Models.ChatRoomModel
                    {
                        ChatRoomId   = foundRoomInDb.Id,
                        Participants = new System.Collections.Generic.List <Models.OnlineUser>
                        {
                            invitor,
                            invitee
                        },
                        RoomName   = invitee.FullName,
                        Type       = RoomType.Double,
                        CreateDate = DateTime.UtcNow
                    };
                    _chatContext.LoadDoubleRoom(chatRoomModel);

                    isExistedOnDb = true;
                    chatRoomId    = foundRoomInDb.Id;
                }
                else
                {
                    // Create new chatroom
                    var chatRoom = new ChatRoom
                    {
                        Id           = DataUtil.GenerateUniqueId(),
                        CreatedDate  = DateTime.UtcNow,
                        Participants = new List <Participant>
                        {
                            new Participant
                            {
                                Id         = DataUtil.GenerateUniqueId(),
                                JoinedDate = DateTime.UtcNow,
                                Username   = invitor.UserName
                            },
                            new Participant
                            {
                                Id         = DataUtil.GenerateUniqueId(),
                                JoinedDate = DateTime.UtcNow,
                                Username   = invitee.UserName
                            }
                        },
                        RoomName = invitee.UserName,
                        Sessions = new List <ChatSession>(),
                        Type     = RoomType.Double
                    };

                    await _chatRoomRepository.AddAsync(chatRoom);

                    chatRoomModel = new Models.ChatRoomModel
                    {
                        ChatRoomId   = chatRoom.Id,
                        Participants = new System.Collections.Generic.List <Models.OnlineUser>
                        {
                            invitor,
                            invitee
                        },
                        RoomName   = invitee.FullName,
                        Type       = RoomType.Double,
                        CreateDate = DateTime.UtcNow
                    };
                    _chatContext.LoadDoubleRoom(chatRoomModel);
                    chatRoomId       = chatRoom.Id;
                    createNewSession = true;
                }
            }
            else
            {
                chatRoomId       = founDoubleRoom.ChatRoomId;
                chatRoomModel    = founDoubleRoom;
                chatSessionModel = _chatContext.GetCurrentChatSession(chatRoomId);
                if (chatSessionModel == null)
                {
                    createNewSession = true;
                }
                else if (!string.IsNullOrEmpty(chatSessionModel.PreviousSessionId))
                {
                    previousSessionModel = _chatContext.GetChatSession(chatSessionModel.PreviousSessionId);
                }
            }

            if (isExistedOnDb)
            {
                // Try to fetch last chat session
                var foundLastSession = await _chatSessionRepository.GetLastChatSession(chatRoomId);

                if (foundLastSession != null)
                {
                    // In mind, we only create new chat session when it reached Threshold
                    // Or it belongs to previous day
                    if (foundLastSession.Conversations.Count >= _chatOptions.CurrentValue.ThresholdNumberOfMessages)
                    {
                        createNewSession = true;
                        // Load previous session
                        previousSessionModel = new ChatSessionModel
                        {
                            ChatRoomId        = chatRoomId,
                            Messages          = new Queue <MessageModel>(),
                            CreatedDate       = foundLastSession.CreatedDate,
                            PreviousSessionId = foundLastSession.PreviousSessionId,
                            SessionId         = foundLastSession.Id
                        };

                        if (foundLastSession.Conversations != null)
                        {
                            foreach (var message in foundLastSession.Conversations.OrderBy(a => a.Timestamp))
                            {
                                previousSessionModel.Messages.Enqueue(new MessageModel
                                {
                                    Message          = message.Message,
                                    FormattedMessage = message.MessageTransform,
                                    TimeStamp        = message.Timestamp,
                                    UserName         = message.Username,
                                    CreatedDate      = message.CreatedDate,
                                    AttachmentFiles  = new List <AttachmentFile>()
                                });
                            }
                        }

                        _chatContext.AddChatRoomSession(previousSessionModel);
                    }
                    else
                    {
                        chatSessionModel = ChatSessionModel.LoadFrom(foundLastSession);

                        // Load one previous session if it had
                        if (!string.IsNullOrEmpty(chatSessionModel.PreviousSessionId))
                        {
                            var previousSession = await _chatSessionRepository.GetOneAsync(chatSessionModel.PreviousSessionId);

                            previousSessionModel = ChatSessionModel.LoadFrom(previousSession);
                        }

                        _chatContext.AddChatRoomSession(chatSessionModel);
                    }
                }
                else
                {
                    createNewSession = true;
                }
            }

            if (createNewSession)
            {
                chatSessionModel = new ChatSessionModel
                {
                    SessionId         = DataUtil.GenerateUniqueId(),
                    ChatRoomId        = chatRoomId,
                    Messages          = new Queue <MessageModel>(),
                    CreatedDate       = DateTime.UtcNow,
                    PreviousSessionId = previousSessionModel?.SessionId
                };

                if (previousSessionModel != null)
                {
                    previousSessionModel.NextSessionId = chatSessionModel.SessionId;
                }

                _chatContext.AddChatRoomSession(chatSessionModel);
            }

            // Allow target user to prepare a chatroom
            await Clients
            .User(invitee.UserName)
            .ReadyDoubleChatRoom(
                chatRoomModel,
                chatSessionModel,
                invitor,
                previousSessionModel);

            await Clients.Caller.LoadDoubleChatRoom(
                chatRoomModel,
                chatSessionModel,
                invitee,
                previousSessionModel);
        }