示例#1
0
            public async Task WhenGetConversationParticipantsGetsCalled()
            {
                Setup();

                AuthService.Setup(service => service.GetUserIdFromToken(It.IsAny <string>())).Returns("not a guid");

                _result = await ConversationsController.GetConversationParticipants(_conversationId);
            }
示例#2
0
            public async Task WhenGetConversationsGetsCalled()
            {
                Setup();

                AuthService.Setup(service => service.AuthorizeSelf(It.IsAny <string>(), It.IsAny <Guid>())).Returns(false);

                _result = await ConversationsController.GetConversations(_userId);
            }
示例#3
0
 public async Task WhenGetConversationsGetsCalled()
 {
     Setup();
     _createConversationRequest.SenderId   = Guid.NewGuid();
     _createConversationRequest.ReceiverId = Guid.NewGuid();
     _createConversationRequest.Content    = "Hi Bob!";
     AuthService.Setup(service => service.AuthorizeSelf(
                           It.IsAny <string>(), It.IsAny <Guid>())).Returns(false);
     _result = await ConversationsController.CreateConversation(_createConversationRequest);
 }
示例#4
0
 public void Initialize()
 {
     mockStore    = new Mock <IConversationStore>();
     mockLogger   = new Mock <ILogger <ConversationsController> >();
     mockService  = new Mock <INotificationServiceClient>();
     profileStore = new Mock <IProfileStore>();
     mockClient   = TestUtils.GenerateClient();
     myController = new ConversationsController(mockStore.Object, mockClient, mockLogger.Object,
                                                profileStore.Object, mockService.Object);
 }
示例#5
0
            public async Task WhenGetConversationParticipantsGetsCalled()
            {
                Setup();

                AuthService.Setup(service => service.GetUserIdFromToken(It.IsAny <string>())).Returns(_userId.ToString());
                ConversationsService.Setup(service => service.GetConversationParticipants(It.IsAny <Guid>()))
                .ReturnsAsync(new Fixture().CreateMany <Guid>().ToList());

                _result = await ConversationsController.GetConversationParticipants(_conversationId);
            }
示例#6
0
        public static void FunctionC([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"C# Timer trigger function2 executed at: {DateTime.Now}");
            FunctionTickets Tickets = new FunctionTickets();

            Tickets.TicketsFunction(context, "/tickets");

            ConversationsController Conversation = new ConversationsController();

            Conversation.ConversationsUpdate(context, "/tickets");
        }
        public async Task ListConversationsReturns404WhenProfileNotFoundExceptionIsThrown()
        {
            conversationsStoreMock.Setup(store => store.ListConversations(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()))
            .ThrowsAsync(new ProfileNotFoundException("test failure"));

            var           conversationsController = new ConversationsController(conversationsStoreMock.Object, profileStoreMock.Object, loggerMock.Object, metricsMock.Object, notificationServiceMock.Object);
            IActionResult result = await conversationsController.ListConversations(
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);

            TestUtils.AssertStatusCode(HttpStatusCode.NotFound, result);
        }
        public async Task ListConversationsReturns500WhenUnknownExceptionIsThrown()
        {
            conversationsStoreMock.Setup(store => store.ListConversations(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()))
            .ThrowsAsync(new UnknownException());

            var           conversationsController = new ConversationsController(conversationsStoreMock.Object, profileStoreMock.Object, loggerMock.Object, metricsMock.Object, notificationServiceMock.Object);
            IActionResult result = await conversationsController.ListConversations(
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);

            TestUtils.AssertStatusCode(HttpStatusCode.InternalServerError, result);
        }
        public ConversationsController GetController(bool setHttpContext = true)
        {
            var controller = new ConversationsController(TestInitializator.GetContext(), TestInitializator.GetUserManager().Object);

            if (setHttpContext)
            {
                controller.ControllerContext.HttpContext = TestInitializator.GetHttpContext().Object;
            }

            return(controller);
        }
        public async Task ListConversationsReturns503WhenStorageIsUnavailable()
        {
            conversationsStoreMock.Setup(store => store.ListConversations(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()))
            .ThrowsAsync(new StorageErrorException("Test Failure"));

            var           conversationsController = new ConversationsController(conversationsStoreMock.Object, profileStoreMock.Object, loggerMock.Object, metricsMock.Object, notificationServiceMock.Object);
            IActionResult result = await conversationsController.ListConversations(
                Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);

            TestUtils.AssertStatusCode(HttpStatusCode.ServiceUnavailable, result);
        }
示例#11
0
            public async Task WhenCreateConversationGetsCalled()
            {
                Setup();

                AuthService.Setup(service => service.AuthorizeSelf(
                                      It.IsAny <string>(), It.IsAny <Guid>())).Returns(true);
                ConversationsService.Setup(service => service.CreateConversationWithParticipants(
                                               _createConversationRequest.SenderId, _createConversationRequest.ReceiverId))
                .ReturnsAsync(_conversationId);

                _result = await ConversationsController.CreateConversation(_createConversationRequest);
            }
        protected void Setup()
        {
            AuthService           = new Mock <IAuthService>();
            ConversationsService  = new Mock <IConversationsService>();
            MessagesService       = new Mock <IMessagesService>();
            ConversationValidator = new Mock <IConversationValidator>();

            ConversationsController = new ConversationsController(AuthService.Object, ConversationsService.Object, MessagesService.Object, ConversationValidator.Object);
            ConversationsController.ControllerContext             = new ControllerContext();
            ConversationsController.ControllerContext.HttpContext = new DefaultHttpContext();
            ConversationsController.ControllerContext.HttpContext.Request.Headers.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJCb2IgSmVua2lucyIsImp0aSI6IjAzZTE2MGMyLWZhNWItNDg0NS1hMjMwLTU5MDZlZTU1NWY1ZSIsImV4cCI6MTg5MzcwMTYyNywiaXNzIjoibG9jYWxob3N0OjUwMDEiLCJhdWQiOiJsb2NhbGhvc3Q6NTAwMSJ9.C9_Y29A0ky2tObFpp7vyvm3vjlxSU4Tmfj_B1Mvyfh4");
        }
        public async Task PostMessageReturns503WhenStorageIsDown()
        {
            var conversationsServiceMock = new Mock <IConversationsService>();

            conversationsServiceMock.Setup(store => store.PostMessage(_testConversation.Id, _testPostMessageRequest)).ThrowsAsync(new StorageErrorException());

            var           loggerStub = new ConversationsControllerLoggerStub();
            var           controller = new ConversationsController(conversationsServiceMock.Object, loggerStub, new TelemetryClient());
            IActionResult result     = await controller.PostMessage(_testConversation.Id, _testPostMessageRequest);

            AssertUtils.HasStatusCode(HttpStatusCode.ServiceUnavailable, result);
            Assert.Contains(LogLevel.Error, loggerStub.LogEntries.Select(entry => entry.Level));
        }
        public async Task GetMessageListReturns500WhenExceptionIsNotKnown()
        {
            var conversationsServiceMock = new Mock <IConversationsService>();

            conversationsServiceMock.Setup(store => store.GetMessageList(_testConversation.Id, _testContinuationToken, _testLimit, _lastSeenTime)).ThrowsAsync(new Exception("Test Exception"));

            var           loggerStub = new ConversationsControllerLoggerStub();
            var           controller = new ConversationsController(conversationsServiceMock.Object, loggerStub, new TelemetryClient());
            IActionResult result     = await controller.GetMessageList(_testConversation.Id, _testContinuationToken, _testLimit, _lastSeenTime);

            AssertUtils.HasStatusCode(HttpStatusCode.InternalServerError, result);
            Assert.Contains(LogLevel.Error, loggerStub.LogEntries.Select(entry => entry.Level));
        }
        public async Task GetConversationsReturns503WhenStorageIsDown()
        {
            var conversationsServiceMock = new Mock <IConversationsService>();

            conversationsServiceMock.Setup(store => store.GetConversations(_testUsername, _testContinuationToken, _testLimit, _lastSeenTime)).ThrowsAsync(new StorageErrorException());

            var           loggerStub = new ConversationsControllerLoggerStub();
            var           controller = new ConversationsController(conversationsServiceMock.Object, loggerStub, new TelemetryClient());
            IActionResult result     = await controller.GetConversations(_testUsername, _testContinuationToken, _testLimit, _lastSeenTime);

            AssertUtils.HasStatusCode(HttpStatusCode.ServiceUnavailable, result);
            Assert.Contains(LogLevel.Error, loggerStub.LogEntries.Select(entry => entry.Level));
        }
        public async Task CreateConversationReturns503WhenStorageIsUnavailable()
        {
            conversationsStoreMock.Setup(store => store.AddConversation(It.IsAny <Conversation>()))
            .ThrowsAsync(new StorageErrorException("Test Failure"));

            CreateConversationDto newConversation = new CreateConversationDto()
            {
                Participants = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }
            };

            var           conversationsController = new ConversationsController(conversationsStoreMock.Object, profileStoreMock.Object, loggerMock.Object, metricsMock.Object, notificationServiceMock.Object);
            IActionResult result = await conversationsController.CreateConversation(
                newConversation);

            TestUtils.AssertStatusCode(HttpStatusCode.ServiceUnavailable, result);
        }
        public async Task CreateConversationReturns500WhenUnknownExceptionIsThrown()
        {
            conversationsStoreMock.Setup(store => store.AddConversation(It.IsAny <Conversation>()))
            .ThrowsAsync(new UnknownException());

            CreateConversationDto newConversation = new CreateConversationDto()
            {
                Participants = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }
            };

            var           conversationsController = new ConversationsController(conversationsStoreMock.Object, profileStoreMock.Object, loggerMock.Object, metricsMock.Object, notificationServiceMock.Object);
            IActionResult result = await conversationsController.CreateConversation(
                newConversation);

            TestUtils.AssertStatusCode(HttpStatusCode.InternalServerError, result);
        }
示例#18
0
        public async Task PostAsync([FromBody] JObject MessageJobj)
        {
            bool   outgoing;
            string ChannelUUId = "";

            string SocketPublishUrl = _configuration.GetValue <string>("RequestUrls:WebSocketPublish");

            string MdeiaType = "0";

            LogProperties.info("Whats api called");


            try

            {
                outgoing = (bool)MessageJobj["outgoing"];
                //               "sender": "919966226645",
                //"recipient": "2df4b63c-135a-4206-91d3-8132dfe64f22",
                if (!outgoing)
                {
                    ChannelUUId = Convert.ToString(MessageJobj["recipient"]);
                }

                WidgetChannels widgetChannel = null;
                Widgets        widget        = null;
                try
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == widgetChannel.WidgetId).FirstOrDefault();
                    LogProperties.info("widget for message: " + widgetChannel.WidgetId);
                }
                catch (Exception dbEx)
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.Id == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message catch: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == 6).FirstOrDefault();
                    LogProperties.info("widget for message catch: " + widget.Id);
                }
                // var widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                // LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId );



                //[HttpPost("{account_id}/widgets/{widget_id}/conversations/{conversation_id}/{is_endchat}/replies")]
                if (widget != null)
                {
                    if (!outgoing)
                    {
                        JObject jObject = new JObject();
                        jObject = JObject.Parse(MessageJobj.ToString());
                        //    await ProcessIncomingMessageAsync(widget, MessageJobj);

                        LogProperties.info("Whats api ougoing enter");
                        string CustomerMobile       = "";
                        string CustomerName         = "";
                        string CustomerProfileImage = "";

                        int     AccountId              = widget.AccountId;
                        int     WidgetId               = widget.Id;
                        int     ConverstationId        = 0;
                        long    ConverstationMessageId = 0;
                        int     CustomerId             = 0;
                        JObject CustJobj               = new JObject();

                        CustomerMobile       = Convert.ToString(MessageJobj["sender"]);
                        ChannelUUId          = Convert.ToString(MessageJobj["recipient"]);
                        CustomerName         = Convert.ToString(MessageJobj["payload"]["user"]["name"]);
                        CustomerProfileImage = Convert.ToString(MessageJobj["payload"]["user"]["image"]);

                        ConversationsController conController = new ConversationsController(_context, _configuration);



                        CustJobj   = GetCustomerId(AccountId, CustomerName, CustomerMobile, CustomerProfileImage);
                        CustomerId = Convert.ToBoolean(CustJobj["Success"]) ? Convert.ToInt32(CustJobj["CustomerId"]) : -1;
                        LogProperties.info("Whats api after get customer");
                        var PrevConverstations = (from Con in _context.Conversations
                                                  where Con.WidgetId == WidgetId && Con.CustomerId == CustomerId
                                                  orderby Con.Id descending
                                                  select new {
                            Con.Id,
                            Con.AgentId
                        }).FirstOrDefault();

                        if (PrevConverstations != null)
                        {
                            ConverstationId = PrevConverstations.Id;
                        }
                        LogProperties.info("Whats api after Conversations");
                        var PrevConMessages = (from ConMess in _context.ConversationMessages
                                               where ConMess.ConversationId == ConverstationId
                                               orderby ConMess.Id descending
                                               select new
                        {
                            ConMess.Id,
                            ConMess.CreatedTimeUTC,
                            ConMess.AgentId
                        }).FirstOrDefault();

                        DateTime RecentMsgTime;
                        if (PrevConMessages != null && PrevConMessages.Id > 0)
                        {
                            ConverstationMessageId = PrevConMessages.Id;
                            RecentMsgTime          = PrevConMessages.CreatedTimeUTC;
                        }
                        else
                        {
                            RecentMsgTime = DateTime.Today.AddDays(-10);
                        }

                        LogProperties.info("Whats api after Conversation messages");

                        DateTime CurrentUtcNow = DateTime.UtcNow;
                        TimeSpan MessageSpan   = CurrentUtcNow - RecentMsgTime;


                        double totalSecForDay = 3 * 60 * 60;           // Static condiftion
                        bool   IsNewChat      = false;
                        if (MessageSpan.TotalSeconds > totalSecForDay) // create new conversations after 24 hours
                        {
                            Conversations conversations = new Conversations()
                            {
                                StatusId           = 1,
                                CustomerId         = CustomerId,
                                Mobile             = CustomerMobile,
                                ConversationTypeId = 2
                            };


                            ActionResult <Conversations> newCon = await conController.PostConversations(AccountId, WidgetId, conversations);

                            // JObject Con = await CreateConversation(AccountId, WidgetId, conversations);

                            OkObjectResult okResult = newCon.Result as OkObjectResult;

                            if (okResult.StatusCode == 200)
                            {
                                Conversations NewConversation = okResult.Value as Conversations;
                                ConverstationId = NewConversation.Id;
                            }



                            IsNewChat = true;
                        }
                        LogProperties.info("Whats api after Conversation save");
                        ConversationMessages conversationMessages = new ConversationMessages();
                        int IsBotEnd = 0;
                        //"MessageTypeId": "1",
                        //    "Message":msg
                        conversationMessages.ConversationId     = ConverstationId;
                        conversationMessages.MessageTypeId      = 1;
                        conversationMessages.ConversationTypeId = 2;

                        if (IsNewChat == false)
                        {
                            conversationMessages.AgentId = PrevConverstations.AgentId;
                        }
                        //message payload table
                        conversationMessages.Message = Convert.ToString(MessageJobj["payload"]["text"]);
                        string CustomerMessage = Convert.ToString(MessageJobj["payload"]["text"]);

                        string MessageType = Convert.ToString(MessageJobj["payload"]["type"]);


                        if (MessageType != "text")
                        {
                            //attachment

                            conversationMessages.AttachmentUrl = Convert.ToString(MessageJobj["payload"]["attachment"]);

                            conversationMessages.Message = ConstructMediaMessage(conversationMessages.AttachmentUrl, MessageType, conversationMessages.Message, ref MdeiaType);
                        }


                        var ConInfo = _context.ConversationInfo.Where(w => w.ConversationId == ConverstationId).FirstOrDefault();
                        if (ConInfo != null)
                        {
                            IsBotEnd = ConInfo.IsBotEnd;
                        }
                        if (IsBotEnd > 0)
                        {
                            conversationMessages.MessageTypeId = 3;
                        }
                        ActionResult <ConversationMessages> newConMsg = await conController.PostConversationMessages(AccountId, WidgetId, ConverstationId, IsBotEnd, conversationMessages);



                        OkObjectResult okResultMesg = newConMsg.Result as OkObjectResult;

                        if (okResultMesg.StatusCode == 200)
                        {
                            ConversationMessages NewConvMsg = okResultMesg.Value as ConversationMessages;
                        }

                        LogProperties.info("Whats api after Conversation message save");

                        if (IsBotEnd > 0)
                        {
                            // table for botend

                            //if (IsPingAgent == "true")
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": conversationId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            //else
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": fromId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            if (IsNewChat == false && IsBotEnd > 0) // send message to agent through socket
                            {
                                //JObject jobj = new JObject();
                                //jobj.Add(new JProperty("conversationId", conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("from", "WhatsApp_"+ conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("to", "Hub_" + conversationMessages.AgentId));
                                //jobj.Add(new JProperty("message", conversationMessages.Message));
                                //jobj.Add(new JProperty("messageType", "0"));

                                //WebSocketSubscriber.Send(jobj);

                                JObject jobjs        = new JObject();
                                JObject wsMessageObj = new JObject();


                                JObject CustomerDetails = new JObject();

                                //                "data":{"fromName" :"" ,"fromMobile",""}

                                CustomerDetails.Add(new JProperty("fromName", CustomerName));
                                CustomerDetails.Add(new JProperty("fromMobile", CustomerMobile));

                                jobjs.Add(new JProperty("conversationId", Convert.ToString(ConverstationId)));
                                jobjs.Add(new JProperty("from", "WhatsApp_5f2d3a8e31197a445686653b"));
                                jobjs.Add(new JProperty("to", "Hub_" + PrevConverstations.AgentId));
                                jobjs.Add(new JProperty("message", CustomerMessage));
                                jobjs.Add(new JProperty("mediaUrl", conversationMessages.AttachmentUrl));
                                jobjs.Add(new JProperty("type", MdeiaType));
                                jobjs.Add(new JProperty("data", CustomerDetails));
                                jobjs.Add(new JProperty("messageType", "0"));
                                jobjs.Add(new JProperty("ConversationTypeId", 2));

                                wsMessageObj = new JObject(new JProperty("Module", "Chat"),
                                                           new JProperty("Event", "NewChat"),
                                                           new JProperty("Channel_Name", "WhatsApp_Hub_" + PrevConverstations.AgentId),
                                                           new JProperty("Data", jobjs));


                                // WebSocketSubscriber wb = new WebSocketSubscriber();
                                WebSocketSubscriber.pushSocket(SocketPublishUrl, wsMessageObj);

                                LogProperties.info("Whats api after websocket publish");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogProperties.error("expection at WhatsApp Handler: " + ex.ToString());
            }
        }