public async Task <WhatsappResponse> ProcessRequest(Dictionary <string, string> pars)
        {
            try
            {
                var whatsappMessage = new WhatsappMessage(pars);
                await _auditStore.AuditMessage(whatsappMessage);

                // Check in cache (or table) if phone Number is linked
                var userInfo = await _userStore.GetUserInfo(whatsappMessage.Sender);

                if (whatsappMessage.IsSystemMessage(out var userCommand))
                {
                    return(await ProcessSystemMessage(userCommand, userInfo, whatsappMessage));
                }

                if (!string.IsNullOrEmpty(userInfo?.BoxInfo?.BoxId))
                {
                    return(await ProcessAuthenticatedMessage(userInfo, whatsappMessage));
                }

                // This is for users that are not yet linked to a tenant
                return(await ProcessUnauthenticatedMessage(userInfo, whatsappMessage));
            }
            catch (Exception e)
            {
                _logger.LogError(e,
                                 $"An error happened while processing the incoming WhatsApp message with parameters {pars}");
                throw;
            }
        }
Exemple #2
0
        public async Task <bool> SendAsync(WhatsappMessage message, CancellationToken cancellationToken)
        {
            TwilioClient.Init(_notificationSettings.WhatsApp.Username, _notificationSettings.WhatsApp.Password);
            var messageResource = await MessageResource.CreateAsync(
                to : new PhoneNumber($"whatsapp:{_notificationSettings.WhatsApp.SenderContactNumber}"),
                from : new PhoneNumber($"whatsapp:{message.PhoneNumber}"),
                body : message.Text
                );

            return(messageResource != null && string.IsNullOrEmpty(messageResource.Sid));
        }
        private async Task <WhatsappResponse> ProcessSystemMessage(UserCommand userCommand, UserInfo userInfo,
                                                                   WhatsappMessage whatsappMessage)
        {
            string responseMessage;

            object[] pars     = { userInfo.Name };
            bool     accepted = false;

            switch (userCommand)
            {
            case UserCommand.LeaveBox:
                userInfo.ConversationState = ConversationState.AwaitingActivation;
                userInfo.BoxInfo           = null;
                pars = new object[] { userInfo.Name };
                await _userStore.UpdateUser(userInfo);

                _logger.LogWarning("The user {phoneNumber} got discoupled from the box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                responseMessage = "We hebben u ontkoppeld van de box, {0}";
                accepted        = true;
                break;

            case UserCommand.ViewBox:
                _logger.LogWarning("The user {phoneNumber} asked a view link for the box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                if (!string.IsNullOrEmpty(userInfo.BoxInfo?.BoxId))
                {
                    pars            = new object[] { $"https://coditfamilyview.azurewebsites.net?boxId={userInfo.BoxInfo.BoxId}" };
                    responseMessage = "U kan hier de box zien: {0}";
                    accepted        = true;
                }
                else
                {
                    pars            = new object[] { userInfo.Name };
                    responseMessage = "U bent nog niet gekoppeld aan een box, {0}";
                }
                break;

            default:
                responseMessage =
                    $"Het spijt ons, maar we hebben nog geen ondersteuning voor het commando {whatsappMessage.MessageContent}";
                break;
            }

            return(new WhatsappResponse
            {
                ResponseMessage = (await _messageTranslater.Translate(userInfo.GetLanguage(), responseMessage, pars)),
                Accepted = accepted
            });
        }
        private async Task <WhatsappResponse> ProcessText(UserInfo userInfo, WhatsappMessage message)
        {
            string userMessage = $"Bericht van {userInfo.Name}({userInfo.PhoneNumber}): {message}";
            await _messageServiceProvider.PersistTextMessage(userInfo, new TextMessage
            {
                From           = userInfo.Name,
                PhoneNumber    = userInfo.PhoneNumber,
                Message        = message.MessageContent,
                ExpirationTime = DateTimeOffset.UtcNow.AddDays(1)
            });

            _logger.LogEvent("New Message Received");
            _logger.LogMetric("Text Received", 1);

            return(new WhatsappResponse
            {
                ResponseMessage = await _messageTranslater.Translate(userInfo.GetLanguage(),
                                                                     "We ontvingen je bericht, {0}", userInfo.Name),
                Accepted = true
            });
        }
        private async Task <WhatsappResponse> ProcessImages(UserInfo userInfo, WhatsappMessage message)
        {
            foreach (var mediaItem in message.MediaItems)
            {
                await _imageServiceProvider.PersistMediaFile(userInfo, WebUtility.UrlDecode(mediaItem.Url));

                _logger.LogEvent("New Image Received");
                _logger.LogMetric("Image Received", 1);
            }

            string responseMessage = message.MediaItems.Count == 1
                ? await _messageTranslater.Translate(userInfo.GetLanguage(), "We stuurden je foto door, {0}",
                                                     userInfo.Name)
                : await _messageTranslater.Translate(userInfo.GetLanguage(), "We stuurden je {0} foto's door, {0}",
                                                     message.MediaItems.Count, userInfo.Name);

            return(new WhatsappResponse
            {
                ResponseMessage = responseMessage,
                Accepted = true
            });
        }
        private async Task <WhatsappResponse> ProcessUnauthenticatedMessage(UserInfo userInfo, WhatsappMessage message)
        {
            string responseMessage;

            object[] pars = { userInfo.Name };

            string messageBody = message.MessageContent;
            string mediaUrl    = null;

            switch (userInfo.ConversationState)
            {
            case ConversationState.New:
                await _userStore.CreateUser(userInfo.PhoneNumber, null, ConversationState.AwaitingName);

                responseMessage = "Welkom bij deze app, wat is uw naam, aub?";
                break;

            case ConversationState.AwaitingName:
                userInfo.Name = messageBody;
                userInfo.ConversationState = ConversationState.AwaitingActivation;
                pars = new object[] { userInfo.Name };
                await _userStore.UpdateUser(userInfo);

                responseMessage =
                    "Welkom, {0}, als je een client wil connecteren, gelieve dan de activatiecode te sturen.  Die kan je bekomen door de eerste letters te nemen van de icoontjes op het scherm van de box.  In het voorbeeld is het bijvoorbeeld HOME";
                mediaUrl = "https://codithtc.blob.core.windows.net/public/media/example.png";
                break;

            case ConversationState.AwaitingActivation:
                responseMessage = await HandleBoxActivation(userInfo, messageBody);

                break;

            case ConversationState.Completed:
                _logger.LogWarning(
                    "User {phoneNumber} ended up in the unauthenticated conversation part, although the conversation state was completed",
                    userInfo.PhoneNumber);
                responseMessage =
                    "Normaal mag je nu gewoon foto's en berichten beginnen sturen en mag je dit niet meer krijgen";
                break;

            default:
                _logger.LogWarning(
                    "User {phoneNumber} ended up in the unauthenticated conversation part, although the conversation state was completed",
                    userInfo.PhoneNumber);
                responseMessage = "We konden uw bericht niet correct interpreteren.  Gelieve opnieuw te proberen";
                break;
            }

            return(new WhatsappResponse
            {
                ResponseMessage = (await _messageTranslater.Translate(userInfo.GetLanguage(), responseMessage, pars)),
                ImageUrl = mediaUrl,
                Accepted = true
            });
        }
        private async Task <WhatsappResponse> ProcessAuthenticatedMessage(UserInfo userInfo, WhatsappMessage message)
        {
            // This is handling a user that is already linked to a tenant
            _logger.LogTrace(
                $"Processing message from user {userInfo.Name} and phone nr {userInfo.PhoneNumber} in tenant {userInfo.BoxInfo.BoxId}");
            if (message.MediaItems.Count > 0)
            {
                return(await ProcessImages(userInfo, message));
            }

            return(await ProcessText(userInfo, message));
        }
        public JsonResult SendRequest(string _type)
        {
            WhatsappComminucation c = null;

            using (var context = new ProjectManagementEntities())
            {
                c = new WhatsappComminucation()
                {
                    Date     = DateTime.Now,
                    Request  = _type,
                    Response = null
                };
                context.WhatsappComminucation.Add(c);
                context.SaveChanges();
            }

            while (c.Response == null)
            {
                using (var context = new ProjectManagementEntities())
                {
                    c = context.WhatsappComminucation.FirstOrDefault(x => x.Id == c.Id);
                }
            }

            if (!c.Response.StartsWith("data:image/png;base64") && c.Response != "true")
            {
                var model = JsonConvert.DeserializeObject <List <Whatsapp> >(c.Response);

                using (var context = new ProjectManagementEntities())
                {
                    foreach (var item in model)
                    {
                        item.SonMesaj = HttpUtility.HtmlDecode(item.SonMesaj);
                        item.Gonderen = HttpUtility.HtmlDecode(item.Gonderen);

                        var lastMesaj = context.WhatsappMessage.Where(x => x.MessageFrom == item.Gonderen && x.IsSeen == false).ToList().OrderByDescending(x => x.Id).ToList().FirstOrDefault();

                        if (lastMesaj != null)
                        {
                            if ((DateTime.Now - lastMesaj.Date).TotalMinutes <= 5)
                            {
                                if (!lastMesaj.MessageContent.Contains(item.SonMesaj))
                                {
                                    lastMesaj.MessageContent = lastMesaj.MessageContent + "||=>||" + item.SonMesaj;
                                    lastMesaj.Date           = DateTime.Now;
                                    context.SaveChanges();
                                }
                            }
                            else
                            {
                                var allMessages = string.Join("||=>||", context.WhatsappMessage.Where(x => x.MessageFrom == item.Gonderen).Select(x => x.MessageContent));

                                if (allMessages == item.SonMesaj || allMessages.Contains("||=>||" + item.SonMesaj) || allMessages.Contains(item.SonMesaj + "||=>||"))
                                {
                                }
                                else
                                {
                                    var insertObj = new WhatsappMessage()
                                    {
                                        Date           = DateTime.Now,
                                        IsSeen         = false,
                                        MessageContent = item.SonMesaj,
                                        MessageFrom    = item.Gonderen
                                    };
                                    context.WhatsappMessage.Add(insertObj);
                                    context.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            var allMessages = string.Join("||=>||", context.WhatsappMessage.Where(x => x.MessageFrom == item.Gonderen).Select(x => x.MessageContent));

                            if (allMessages == item.SonMesaj || allMessages.Contains("||=>||" + item.SonMesaj) || allMessages.Contains(item.SonMesaj + "||=>||"))
                            {
                            }
                            else
                            {
                                var insertObj = new WhatsappMessage()
                                {
                                    Date           = DateTime.Now,
                                    IsSeen         = false,
                                    MessageContent = item.SonMesaj,
                                    MessageFrom    = item.Gonderen
                                };
                                context.WhatsappMessage.Add(insertObj);
                                context.SaveChanges();
                            }
                        }
                        //var controlList = context.WhatsappMessage.Where(x => x.MessageFrom == item.Gonderen).ToList().OrderBy(x => x.Id).ToList();

                        //if (controlList.Count > 0)
                        //{
                        //    var lastItem = controlList.LastOrDefault();

                        //    if (lastItem.MessageContent == item.SonMesaj && lastItem.MessageFrom == item.Gonderen)
                        //        continue;
                        //}
                    }
                }
            }

            return(Json(c.Response));
        }
        private async Task <WhatsappResponse> ProcessSystemMessage(UserCommand userCommand, UserInfo userInfo,
                                                                   WhatsappMessage whatsappMessage)
        {
            string responseMessage;

            object[] pars     = { userInfo.Name };
            bool     accepted = false;

            switch (userCommand)
            {
            case UserCommand.Statistics:
                _logger.LogWarning("The user {phoneNumber} asked for statitics of box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                if (!String.IsNullOrEmpty(userInfo.BoxInfo?.BoxId))
                {
                    var box = await _boxStore.Get(userInfo.BoxInfo.BoxId);

                    if (box.AdminUserPhone == userInfo.PhoneNumber)
                    {
                        var lastConnectedDateTime = await _boxStore.GetLastConnectedDateTime(userInfo.BoxInfo.BoxId);

                        pars = new object[] {
                            userInfo.Name,
                            box.Status,
                            lastConnectedDateTime.ToString("d MMM yyyy HH:mm:ss"),
                            _userStore.GetUsersFromTenant(userInfo.BoxInfo.BoxId).Result.Count(),
                            _messageServiceProvider.GetItems(userInfo.BoxInfo.BoxId).Result.Count(),
                            _imageServiceProvider.GetItems(userInfo.BoxInfo.BoxId).Result.Count()
                        };
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.AppendLine("{0}, dit zijn de statistics van uw box:");
                        stringBuilder.AppendLine("Box status: {1}");
                        stringBuilder.AppendLine("Laatst geraadpleegde datum: {2}");
                        stringBuilder.AppendLine("Aantal gekoppelde gebruikers: {3}");
                        stringBuilder.AppendLine("Aantal berichten: {4}");
                        stringBuilder.AppendLine("Aantal afbeeldingen: {5}");

                        responseMessage = stringBuilder.ToString();
                    }
                    else
                    {
                        pars            = new object[] { userInfo.Name };
                        responseMessage = "Alleen de Admin van de box kan statistics opvragen {0}.";
                    }
                }
                else
                {
                    pars            = new object[] { userInfo.Name };
                    responseMessage = "U bent nog niet gekoppeld aan een box, {0}";
                }

                break;

            case UserCommand.BoxStatus:
                _logger.LogWarning("The user {phoneNumber} asked for status of box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                if (!String.IsNullOrEmpty(userInfo.BoxInfo?.BoxId))
                {
                    var lastConnectedDateTime = await _boxStore.GetLastConnectedDateTime(userInfo.BoxInfo.BoxId);

                    pars            = new object[] { userInfo.Name, lastConnectedDateTime.ToString("d MMM yyyy HH:mm:ss") };
                    responseMessage = "De box is voor het laatst geraadpleegd op {1}, {0}.";
                }
                else
                {
                    pars            = new object[] { userInfo.Name };
                    responseMessage = "U bent nog niet gekoppeld aan een box, {0}";
                }
                break;

            case UserCommand.ClearMedia:
                _logger.LogWarning("The user {phoneNumber} asked for clearing all media of box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                if (!String.IsNullOrEmpty(userInfo.BoxInfo?.BoxId))
                {
                    var box = await _boxStore.Get(userInfo.BoxInfo.BoxId);

                    if (box.AdminUserPhone == userInfo.PhoneNumber)
                    {
                        await _messageServiceProvider.DeleteContent(userInfo);

                        await _imageServiceProvider.DeleteContent(userInfo);

                        pars            = new object[] { userInfo.Name };
                        responseMessage = "Alle content van de box is verwijderd {0}.";
                    }
                    else
                    {
                        pars            = new object[] { userInfo.Name };
                        responseMessage = "Alleen de Admin van de box kan alle content verwijderen {0}.";
                    }
                }
                else
                {
                    pars            = new object[] { userInfo.Name };
                    responseMessage = "U bent nog niet gekoppeld aan een box, {0}";
                }
                break;

            case UserCommand.LeaveBox:
                userInfo.ConversationState = ConversationState.AwaitingActivation;
                userInfo.BoxInfo           = null;
                pars = new object[] { userInfo.Name };
                await _userStore.UpdateUser(userInfo);

                _logger.LogWarning("The user {phoneNumber} got discoupled from the box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                responseMessage = "We hebben u ontkoppeld van de box, {0}";
                accepted        = true;
                break;

            case UserCommand.ViewBox:
                _logger.LogWarning("The user {phoneNumber} asked a view link for the box {boxId}",
                                   userInfo.PhoneNumber, userInfo.BoxInfo?.BoxId);
                if (!string.IsNullOrEmpty(userInfo.BoxInfo?.BoxId))
                {
                    pars            = new object[] { $"https://coditfamilyview.azurewebsites.net?boxId={userInfo.BoxInfo.BoxId}" };
                    responseMessage = "U kan hier de box zien: {0}";
                    accepted        = true;
                }
                else
                {
                    pars            = new object[] { userInfo.Name };
                    responseMessage = "U bent nog niet gekoppeld aan een box, {0}";
                }
                break;

            default:
                responseMessage =
                    $"Het spijt ons, maar we hebben nog geen ondersteuning voor het commando {whatsappMessage.MessageContent}";
                break;
            }

            return(new WhatsappResponse
            {
                ResponseMessage = (await _messageTranslater.Translate(userInfo.GetLanguage(), responseMessage, pars)),
                Accepted = accepted
            });
        }