public virtual DomainAccessGuard.Session GetValidUser(string paramValue, ItemContextParameters parameters, IConversation conversation)
        {
            var username = paramValue.Replace(" ", "");

            if (string.IsNullOrEmpty(username))
            {
                return(null);
            }

            string regex = @"^(\w[\w\s]*)([\\]{1})(\w[\w\s\.\@]*)$";
            Match  m     = Regex.Match(username, regex);

            if (string.IsNullOrEmpty(m.Value))
            {
                return(null);
            }

            DomainAccessGuard.Session userSession = null;
            if (User.Exists(username))
            {
                userSession = AuthenticationWrapper.GetDomainAccessSessions().FirstOrDefault(
                    s => string.Equals(s.UserName, username, StringComparison.OrdinalIgnoreCase));
            }

            return(userSession);
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var name           = (string)conversation.Data[NameKey].Value;
            var profileItem    = (Item)conversation.Data[ProfileItemKey].Value;
            var profileKeyData = (Dictionary <string, string>)conversation.Data[ProfileKeyValuesKey].Value;
            var keys           = ProfileService.GetProfileKeys(profileItem);

            // profile card value field
            var profileCardValue = ProfileService.GetTrackingFieldValue(profileItem, profileKeyData);

            var fields = new Dictionary <ID, string>
            {
                { Constants.FieldIds.PatternCard.NameFieldId, name },
                { Constants.FieldIds.ProfileCard.ProfileCardValueFieldId, profileCardValue }
            };

            //create pattern card
            var profileCardFolder = profileItem.Axes.GetChild("Profile Cards");
            var newProfileItem    = DataWrapper.CreateItem(profileCardFolder.ID, Constants.TemplateIds.ProfileCardTemplateId, parameters.Database, name, fields);

            var toDb = DataWrapper.GetDatabase("web");

            PublishWrapper.PublishItem(newProfileItem, new[] { toDb }, new[] { DataWrapper.ContentLanguage }, true, false, false);

            return(ConversationResponseFactory.Create(KeyName, string.Format(
                                                          Translator.Text("Chat.Intents.CreateProfileCard.Response"),
                                                          profileItem.DisplayName)));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var profiles     = ProfileService.GetProfiles();
            var patternCards = ProfileService.GetAllPatternCards();
            var profileCards = ProfileService.GetAllProfileCards();

            var patternParents = patternCards.Select(a => a.Paths.ParentPath).Distinct().Count();
            var profileParents = profileCards.Select(a => a.Paths.ParentPath).Distinct().Count();

            var profilesWithoutPatterns = profiles.Count - patternParents;
            var profilesWithoutProfiles = profiles.Count - profileParents;

            var itemList = new List <ListItem>
            {
                new ListItem(string.Format(Translator.Text("Chat.Intents.SetupPersonalization.CreateProfile"))),     // profile
                new ListItem(string.Format(Translator.Text("Chat.Intents.SetupPersonalization.CreatePatternCard"))), // pattern card
                new ListItem(string.Format(Translator.Text("Chat.Intents.SetupPersonalization.CreateProfileCard"))), // profile card
                new ListItem(Translator.Text("Chat.Intents.SetupPersonalization.AssignProfileCard")),                // add profile card to page or search action
                new ListItem(string.Format(Translator.Text("Chat.Intents.SetupPersonalization.CreateGoal"))),
                new ListItem(Translator.Text("Chat.Intents.SetupPersonalization.AssignGoal"))
            };
            var intentList = IntentInputFactory.Create(IntentInputType.LinkList, itemList);

            return(ConversationResponseFactory.Create(KeyName, Translator.Text("Chat.Intents.SetupPersonalization.ToSetup"), true, intentList));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var message = "Hmmm. I'm not sure so I've looked up some possible answers for you";

            var path = Context.Server.MapPath("~/sitecore/shell/sitecore.version.xml");

            if (!File.Exists(path))
            {
                return(ConversationResponseFactory.Create(KeyName, string.Empty));
            }

            string    xmlText = File.ReadAllText(path);
            XDocument xdoc    = XDocument.Parse(xmlText);

            var version = xdoc.Descendants("version").First();
            var major   = version.Descendants("major").First().Value;
            var minor   = version.Descendants("minor").First().Value;

            var searchItems = WebSearchRepository
                              .WebSearch($"{result.Query} in Sitecore {major}.{minor}");

            var options = searchItems.WebPages.Value
                          .Take(3)
                          .Select(a => new ListItem(a.Name, a.Url))
                          .ToList();

            var intentInput = IntentInputFactory.Create(IntentInputType.ExternalLinks, options);

            return(ConversationResponseFactory.Create(KeyName, message, true, intentInput));
        }
예제 #5
0
        public virtual IntentOptionSet DbOptions(ItemContextParameters parameters)
        {
            var dbName            = (!string.IsNullOrEmpty(parameters.Database)) ? parameters.Database : "master";
            var publishingTargets = PublishWrapper.GetPublishingTargets(dbName);

            return(IntentOptionSetFactory.Create(IntentOptionType.Link, publishingTargets.ToList()));
        }
예제 #6
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var name   = (string)conversation.Data[NameKey].Value;
            var points = (int)conversation.Data[PointsKey].Value;
            //var isFailure = (bool) conversation.Data[IsFailureKey];

            var fields = new Dictionary <ID, string>
            {
                { new ID("{AC3BC9B6-46A2-4EAD-AF5E-6BDB532EB832}"), "1" },                      // IsGoal
                // { new ID("{BD5D2A52-027F-4CC8-9606-C5CE6CBBF437}"), isFailure ? "1" : "" },  // IsFailure
                // { new ID("{71EBDEBD-9560-48C6-A66F-E17FC018232C}"), "" },                    // Rule
                { new ID("{AC6BA888-4213-43BD-B787-D8DA2B6B881F}"), name },                     // Name
                { new ID("{33AE0E84-74A0-437F-AB2B-859DFA96F6C9}"), points.ToString() },        // Points
                { Sitecore.FieldIDs.WorkflowState, "{EDCBB550-BED3-490F-82B8-7B2F14CCD26E}" },  // workflow state
                { Sitecore.FieldIDs.Workflow, "{689E2994-4656-4C58-9112-7826CB46EE69}" }        // workflow
            };

            //create goal and folder if needed
            var fromDb      = "master";
            var toDb        = DataWrapper.GetDatabase("web");
            var goalItem    = DataWrapper.GetItemById(Constants.ItemIds.GoalNodeId, fromDb);
            var newGoalItem = DataWrapper.CreateItem(goalItem.ID, Constants.TemplateIds.GoalTemplateId, fromDb, name, fields);

            PublishWrapper.PublishItem(goalItem, new[] { toDb }, new[] { DataWrapper.ContentLanguage }, true, false, false);

            return(ConversationResponseFactory.Create(KeyName, string.Format(Translator.Text("Chat.Intents.CreateGoal.Response"), name)));
        }
예제 #7
0
        public IntentInput GetInput(ItemContextParameters parameters, IConversation conversation)
        {
            var dbName            = (!string.IsNullOrEmpty(parameters.Database)) ? parameters.Database : Settings.MasterDatabase;
            var publishingTargets = PublishWrapper.GetPublishingTargets(dbName);

            return(IntentInputFactory.Create(IntentInputType.LinkList, publishingTargets));
        }
예제 #8
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var toDb      = (Database)conversation.Data[DBKey].Value;
            var rootItem  = (Item)conversation.Data[ItemKey].Value;
            var langItem  = (Language)conversation.Data[LangKey].Value;
            var recursion = (bool)conversation.Data[RecursionKey].Value;
            var related   = (bool)conversation.Data[RelatedKey].Value;

            PublishWrapper.PublishItem(rootItem, new[] { toDb }, new[] { langItem }, recursion, false, related);

            var recursionMessage = recursion
                ? Translator.Text("Chat.Intents.Publish.ResponseRecursion")
                : string.Empty;

            var relatedMessage = related
                ? Translator.Text("Chat.Intents.Publish.ResponseRelated")
                : string.Empty;

            return(ConversationResponseFactory.Create(KeyName, string.Format(
                                                          Translator.Text("Chat.Intents.Publish.Response"),
                                                          rootItem.DisplayName,
                                                          toDb.Name,
                                                          LanguageManager.GetLanguageItem(langItem, toDb).DisplayName,
                                                          recursionMessage,
                                                          relatedMessage)));
        }
예제 #9
0
        public virtual IntentOptionSet RecursionOptions(ItemContextParameters parameters)
        {
            var options = new List <string> {
                "Yes", "No"
            };

            return(IntentOptionSetFactory.Create(IntentOptionType.Link, options));
        }
예제 #10
0
        public virtual Language GetValidLanguage(string paramValue, ItemContextParameters parameters, IConversation conversation)
        {
            var dbName = (!string.IsNullOrEmpty(parameters.Database)) ? parameters.Database : "master";
            var db     = DataWrapper.GetDatabase(dbName);
            var langs  = DataWrapper.GetLanguages(db).Where(a => a.Name.Equals(paramValue)).ToList();

            return(langs.Any() ? langs.First() : null);
        }
예제 #11
0
        public virtual IntentOptionSet RecursionOptions(ItemContextParameters parameters)
        {
            var options = new List <string> {
                Translator.Text("Chat.Intents.Publish.Yes"), Translator.Text("Chat.Intents.Publish.No")
            };

            return(IntentOptionSetFactory.Create(IntentOptionType.Link, options));
        }
예제 #12
0
        public ConversationResponse HandleMessage(Activity activity, ItemContextParameters parameters)
        {
            IConversation conversation = (ConversationHistory.Conversations.Any())
                ? ConversationHistory.Conversations.Last()
                : null;

            var inConversation = conversation != null && !conversation.IsEnded;

            // determine which intent user wants and context
            var result        = LuisService.Query(AppId, activity.Text);
            var requestedQuit =
                result.TopScoringIntent.Intent.ToLower().Equals("quit") &&
                result.TopScoringIntent.Score > 0.4;

            var intent = IntentProvider.GetIntent(AppId, result.TopScoringIntent.Intent);

            // if the user is trying to end or finish a conversation
            if (inConversation && requestedQuit)
            {
                conversation.IsEnded = true;
                return(intent.Respond(null, null, null));
            }

            // start a new conversation if not in one
            if (!inConversation && intent != null && result.TopScoringIntent.Score > 0.4)
            {
                conversation = ConversationFactory.Create(result, intent);
                ConversationHistory.Conversations.Add(conversation);
                inConversation = true;
            }

            if (inConversation)
            {
                // check and request all required parameters of a conversation
                foreach (ConversationParameter p in conversation.Intent.RequiredParameters)
                {
                    if (!TryGetParam(p.ParamName, result, conversation, parameters, p.ParamGetter))
                    {
                        return(RequestParam(p, conversation, parameters));
                    }
                }

                conversation.IsEnded = true;

                return(conversation.Intent.Respond(result, parameters, conversation));
            }

            // determine mood of comment
            var sentiment      = GetSentiment(activity.Text);
            var sentimentScore = (sentiment?.Documents != null && sentiment.Documents.Any())
                ? sentiment.Documents.First().Score
                : 1;

            // is a user frustrated or is their intention unclear
            return((sentimentScore <= 0.4)
                ? IntentProvider.GetIntent(AppId, "frustrated user").Respond(null, null, null)
                : IntentProvider.GetDefaultResponse(AppId));
        }
예제 #13
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var username = (string)conversation.Data[UsernameKey].Value;
            var password = (string)conversation.Data[PasswordKey].Value;

            //CreateUser(Sitecore.Context.Domain, username, password);

            return(ConversationResponseFactory.Create(KeyName, Translator.Text("SearchForm.Intents.Registration.Success")));
        }
예제 #14
0
        public ActionResult Post([FromBody] Activity activity)
        {
            var s = JsonConvert.SerializeObject(activity.ChannelData);
            var d = JsonConvert.DeserializeObject <List <string> >(s);
            ItemContextParameters parameters = (d.Any())
                ? JsonConvert.DeserializeObject <ItemContextParameters>(d[0])
                : new ItemContextParameters();

            if (activity.Type != ActivityTypes.Message)
            {
                return(null);
            }

            var result = !string.IsNullOrWhiteSpace(activity.Text) ? LuisService.Query(ChatSettings.OleApplicationId, activity.Text, true) : null;

            var conversationContext = ConversationContextFactory.Create(
                ChatSettings.OleApplicationId,
                Translator.Text("Chat.Clear"),
                Translator.Text("Chat.ConfirmMessage"),
                "decision - yes",
                "decision - no",
                "frustrated",
                "profile user - quit",
                parameters,
                result);

            var conversation   = conversationContext.GetCurrentConversation();
            var inConversation = conversation?.IsEnded ?? false;
            var isQuestion     = result.Query.Split(new char[] { ' ' }).Take(2).Any(a => QuestionWords.Contains(a));
            var response       = (!inConversation && isQuestion)
                ? IntentProvider.GetIntent(ChatSettings.OleApplicationId, "self - websearch").Respond(result, parameters, conversation);

                : LuisConversationService.ProcessUserInput(conversationContext);
            var newMessage = Regex.Replace(response.Message, "<.*?>", " ");

            var relativePath = $"temp\\ole-{CreateMD5Hash(newMessage)}.mp3";
            var filePath     = $"{Request.PhysicalApplicationPath}{relativePath}";

            var locale      = SpeechLocaleOptions.enUS;
            var voice       = VoiceName.EnUsGuyNeural;
            var gender      = GenderOptions.Male;
            var audioFormat = AudioOutputFormatOptions.Audio24Khz160KBitRateMonoMp3;

            SpeechService.TextToFile(newMessage, filePath, locale, voice, gender, audioFormat);

            var reply = activity.CreateReply(response.Message, "en-US");

            reply.ChannelData = new ChannelData
            {
                Input      = response.Input,
                Selections = response.Selections?.ToDictionary(a => a.Key, b => b.Value.DisplayName) ?? null,
                Action     = response.Action,
                AudioFile  = $"\\{relativePath}"
            };

            return(Json(reply));
        }
예제 #15
0
        public virtual Database GetValidDb(string paramValue, ItemContextParameters parameters, IConversation conversation)
        {
            try {
                return(DataWrapper.GetDatabase(paramValue));
            }
            catch { }

            return(null);
        }
예제 #16
0
        public virtual IntentOptionSet LanguageOptions(ItemContextParameters parameters)
        {
            var dbName = (!string.IsNullOrEmpty(parameters.Database)) ? parameters.Database : "master";
            var db     = DataWrapper.GetDatabase(dbName);

            var options = DataWrapper.GetLanguages(db).Select(a => a.Name).ToList();

            return(IntentOptionSetFactory.Create(IntentOptionType.Link, options));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var sessions     = AuthenticationWrapper.GetDomainAccessSessions().OrderByDescending(s => s.LastRequest);
            var sessionCount = sessions.Count();
            var userNames    = sessions.Select(a => a.UserName);
            var conjunction  = (sessionCount != 1) ? Translator.Text("Chat.Intents.LoggedInUsers.PluralConjunction") : Translator.Text("Chat.Intents.LoggedInUsers.SingularConjuntion");
            var plurality    = (sessionCount != 1) ? Translator.Text("Chat.Intents.LoggedInUsers.PluralLetter") : "";

            return(ConversationResponseFactory.Create(KeyName, $"{string.Format(Translator.Text("Chat.Intents.LoggedInUsers.Response"), conjunction, sessionCount, plurality)} <br/><ul><li>{string.Join("</li><li>", userNames)}</li></ul>"));
        }
        public IntentInput GetInput(ItemContextParameters parameters, IConversation conversation)
        {
            var yes     = Translator.Text("Chat.Parameters.Yes");
            var no      = Translator.Text("Chat.Parameters.No");
            var options = new List <ListItem> {
                new ListItem(yes, yes), new ListItem(no, no)
            };

            return(IntentInputFactory.Create(IntentInputType.LinkList, options));
        }
예제 #19
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var name    = (string)conversation.Data[NameKey].Value;
            var email   = (string)conversation.Data[EmailKey].Value;
            var message = (string)conversation.Data[MessageKey].Value;

            //send email

            return(ConversationResponseFactory.Create(KeyName, Translator.Text("SearchForm.Intents.Contact.Success")));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var sessions     = AuthenticationWrapper.GetDomainAccessSessions().OrderByDescending(s => s.LastRequest);
            var sessionCount = sessions.Count();
            var userNames    = sessions.Select(a => a.UserName);
            var conjunction  = (sessionCount != 1) ? "are" : "is";
            var plurality    = (sessionCount != 1) ? "s" : "";

            return(ConversationResponseFactory.Create($"There {conjunction} {sessionCount} user{plurality}. <br/><ul><li>{string.Join("</li><li>", userNames)}</li></ul>"));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var goals    = ProfileService.GetGoals();
            var response = new StringBuilder();
            var goalList = string.Join("", goals.Select(a => $"<li>{a.DisplayName}</li>"));

            response.AppendFormat(Translator.Text("Chat.Intents.ListGoals.Response"), goals.Count(), $"<ul>{goalList}</ul>");

            return(ConversationResponseFactory.Create(KeyName, response.ToString()));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var intents = Provider.GetServices <IIntent>()
                          .Where(g => g.ApplicationId.Equals(ApplicationId) && !g.DisplayName.Equals(""))
                          .OrderBy(b => b.DisplayName)
                          .Select(i => $"<li>{i.DisplayName}</li>");

            var str = string.Join("", intents);

            return(ConversationResponseFactory.Create(KeyName, $"{Translator.Text("Chat.Intents.About.Response")}: <br/><ul>{str}</ul>"));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var intents = Provider.GetServices <IOleIntent>()
                          .Where(g => g.ApplicationId.Equals(ApplicationId) && !g.Description.Equals(""));

            var list = intents.Select(i => $"<li>{i.Description}</li>");

            var str = string.Join("", list);

            return(ConversationResponseFactory.Create($"{Translator.Text("Chat.Intents.About.Response")}: <br/><ul>{str}</ul>"));
        }
예제 #24
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var toDb      = (Database)conversation.Data[DBKey];
            var rootItem  = (Item)conversation.Data[ItemKey];
            var langItem  = (Language)conversation.Data[LangKey];
            var recursion = (string)conversation.Data[RecursionKey];

            PublishWrapper.PublishItem(rootItem, new[] { toDb }, new[] { langItem }, recursion.Equals("y"), false);

            return(ConversationResponseFactory.Create($"I've published {rootItem.DisplayName} to the {toDb.Name} database in {rootItem.Language.Name.ToUpper()} {(recursion.Equals("y") ? " with it's children" : string.Empty)}"));
        }
예제 #25
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var profileItem = (Item)conversation.Data[ItemKey].Value;
            var profileKeys = ProfileService.GetProfileKeys(profileItem);

            var response       = new StringBuilder();
            var profileKeyList = string.Join("", profileKeys.Select(a => $"<li>{a.DisplayName}</li>"));

            response.AppendFormat(Translator.Text("Chat.Intents.ListProfileKeys.Response"), profileKeys.Count(), profileItem.DisplayName, $"<ul>{profileKeyList}</ul>");

            return(ConversationResponseFactory.Create(KeyName, response.ToString()));
        }
예제 #26
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var intents = Provider.GetServices <IIntentFactory <IIntent> >()
                          .Select(a => a.Create())
                          .Where(g => g.ApplicationId.Equals(ApplicationId) && !g.Description.Equals(""));

            var list = intents.Select(i => $"<li>{i.Description}</li>");

            var str = string.Join("", list);

            return(ConversationResponseFactory.Create($"Here's the list of things I can do: <br/><ul>{str}</ul>"));
        }
        public IntentInput GetInput(ItemContextParameters parameters, IConversation conversation)
        {
            var dbName = (!string.IsNullOrEmpty(parameters.Database)) ? parameters.Database : Settings.MasterDatabase;
            var db     = DataWrapper.GetDatabase(dbName);

            var options = DataWrapper
                          .GetLanguages(db)
                          .Select(l => LanguageManager.GetLanguageItem(l, db))
                          .Select(a => new ListItem(a.DisplayName, a.DisplayName))
                          .ToList();

            return(IntentInputFactory.Create(IntentInputType.LinkList, options));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            if (!AuthenticationWrapper.IsCurrentUserAdministrator())
            {
                return(ConversationResponseFactory.Create(KeyName, Translator.Text("Chat.Intents.KickUser.MustBeAdminMessage")));
            }

            var userSession = (DomainAccessGuard.Session)conversation.Data[UserKey].Value;
            var name        = userSession.UserName;

            AuthenticationWrapper.Kick(userSession.SessionID);

            return(ConversationResponseFactory.Create(KeyName, string.Format(Translator.Text("Chat.Intents.KickUser.Response"), name)));
        }
        public IntentInput GetInput(ItemContextParameters parameters, IConversation conversation)
        {
            var all      = Translator.Text("Chat.Parameters.All");
            var item     = (Item)conversation.Data[ItemParamName].Value;
            var versions = item
                           .Versions
                           .GetVersionNumbers()
                           .Select(a => new ListItem(a.Number.ToString()))
                           .ToList();

            versions.Insert(0, new ListItem(all, all));

            return(IntentInputFactory.Create(IntentInputType.LinkList, versions));
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            List <string> responses = new List <string>()
            {
                Translator.Text("Chat.Intents.Frustrated.1"),
                Translator.Text("Chat.Intents.Frustrated.2"),
                Translator.Text("Chat.Intents.Frustrated.3"),
                Translator.Text("Chat.Intents.Frustrated.4"),
                Translator.Text("Chat.Intents.Frustrated.5"),
                Translator.Text("Chat.Intents.Frustrated.6")
            };

            return(ConversationResponseFactory.Create(KeyName, responses[new Random().Next(0, responses.Count)]));
        }